A free points management plugin for WordPress.
myCRED Logo
myCRED Logo
  • Chapters
    • Chapter I – Introduction
    • Chapter II – Getting Started
    • Chapter III – Add-ons
    • Chapter IV – Premium Add-ons
    • Chapter V – For Developers
    • Chapter VI – Reference Guides
  • Categories
    • Actions
    • Classes
    • Constants
    • Filters
    • Functions
    • Objects
    • Shortcodes
    • Hooks
    • Template Tags
  • Packages
    • mycred/api
    • mycred/badge
    • mycred/balance
    • mycred/banking
    • mycred/content
    • mycred/core
    • mycred/coupon
    • mycred/email
    • mycred/game
    • mycred/log
    • mycred/notice
    • mycred/payment
    • mycred/purchase
    • mycred/rank
    • mycred/transfer
  • Store
  • Download
Chapter I
Introduction
  1. The Plugin
  2. Points
  3. The Log
  4. Administration
  5. Automatic Points
  6. Multisites
    • Master Template
    • Central Logging
  7. Add-ons
  8. Supported Plugins
  9. BuddyPress
  10. Usage Examples
  11. Limitations
Chapter II
Getting Started
  1. Installation
  2. Point Type Settings
  3. Multiple Point Types
  4. Adjusting Balances
  5. Setup Hooks
  6. Import Data
    • Importing Balances
    • Importing Log Entries
    • Import CubePoints
  7. Export Data
  8. Widgets
  9. Shortcodes
  10. Optimization
  11. Uninstall
Chapter III
Add-ons
  1. Badges
    • Creating Badges
    • Manual Badges
    • Displaying Badges
    • Developer Resources
  2. Banking
    • Central Banking
    • Compound Interest
    • Recurring Payout
    • Developer Resources
  3. buyCRED
    • Selling Points
    • Add-on Setup
    • Payment Gateways
    • The Checkout Page
    • Pending Payments
    • Developer Resources
  4. Coupons
    • Creating Coupons
    • Redeeming Coupons
    • Coupon Management
    • Developer Resources
  5. Email Notifications
    • Add-on Setup
    • Creating Emails
    • Unsubscribe
    • Developer Resources
  6. Gateway
    • WooCommerce
    • WP E-Commerce
    • Event Espresso
    • Events Manager
    • Developer Resources
  7. Notifications
    • Troubleshooting
    • Developer Resources
  8. Ranks
    • Introduction
    • Add-on Setup
    • Create New Rank
    • Displaying Ranks
    • Developer Resources
  9. Sell Content
    • Add-on Setup
    • Manual Mode
    • Available Shortcodes
    • Troubleshooting
    • Developer Resources
  10. Statistics
    • Available Shortcodes
    • Settings
    • For Developers
  11. Transfers
    • Add-on Setup
    • Available Shortcodes
    • Transfer Messages
    • Transfer Types
    • Developer Resources
Chapter IV
Premium Add-ons
  1. The myCred Store
  2. buyCRED Gateways
    • Stripe
    • Payza
    • Wepay
    • PayFast
    • 2checkout
    • Coinbase
    • ComproPago
    • Paymentwall
    • Robokassa
    • CoinPayments
  3. Third-party Bridges
    • myCred Beaver Builder
    • myCred WCVendors
    • LifterLMS Plugin Integration with myCred
    • myCred Gutenberg
    • myCred Dokan
    • myCred Elementor
    • myCred for WPBakery Page Builder
    • myCred for UserPro
    • myCred for Users Ultra
  4. Games
    • myCred PacMan
    • myCred Learndash
    • Fortune Wheel Addon
    • Lottery Add-on
    • Scratch Cards Add-on
    • Custom Set for Scratch Card Add-on
  5. Enhancements
    • Level Cred Add-on
    • myCred Expiration Add on
    • myCred REST API
    • myCred Reset Point Add on
    • Progress Bar
    • Notifications Plus
    • Social Share Add on
    • Transfer Plus
    • Twilio Transfers
    • Video Add-on
    • Video Add-on for JW Player
    • BuddyPress Charges
    • Partial Payments – WooCommerce
  6. Store Gateways
    • Jigoshop
    • Easy Digital Downloads
    • WPMUDEV Fundraising
  7. Freebies
    • BP Group Leaderboards
    • myCred for Events Manager Pro
Chapter V
For Developers
  1. Introduction
  2. White Labeling
  3. Flowcharts
  4. Playing with Balances
  5. myCRED Objects
  6. Log API
  7. Hook API
  8. Module API
  9. Gateway API
  10. Remote API
    • Version 1.0
    • Version 2.0
  11. Front-end Encryption
Chapter VI
Reference Guides
  1. Log References
  2. Shortcodes
  3. Template Tags
  4. Globals
  5. Constants
  6. Actions
  7. Filters
  8. Objects
  9. Functions
  10. Classes

myCRED_Hook

Package: mycred/core Category: Classes
Description

This is an abstract class used to construct myCRED Hooks. It contains a set of predefined methods to help hook constructions.

Available since version 1.0

Class Properties
Property Declared Type Description
$id Public string The hook ID. Must be unique.
$core Public object The main point type object.
$point_types Public array All registered point type IDs.
$is_main_type Public bool True if the current instance is the main point type (first instance) or false if not.
$mycred_type Public bool The current point type instance.
$prefs Public array Associative array of the hooks saved settings.
Interacting with the Class

As an abstract class, your use this by extending your own hook class.

class myCRED_Custom_Hook extends myCRED_Hook {

	function __construct( $hook_prefs, $type = MYCRED_DEFAULT_TYPE_KEY ) {

		parent::__construct( array(
			'id'       => 'hookid',
			'defaults' => array(
				'creds'   => 10,
				'log'     => '%plural% for a specific event'
			)
		), $hook_prefs, $type );

	}

}
Class Parameters
Parameter Type Required Description
$args array Yes The hook arguments containing the hooks ID and preferences.
$hook_prefs array Yes The module settings array.
$type string Yes The point type key instance.
Class Methods

When using this class, the only requirement is that your class must define and setup it’s own run() method, all other methods are optional and not required to use.

public function run() {
Description: If a hook is enabled, this method is run for each point type instance.
Variable Type Required Description
No variables
}
public function preferences() {
Description: Method that displays the hooks settings in the admin area. If this method is not defined in your class, the hook will appear to have no settings when viewed in the admin area.
Variable Type Required Description
No variables
}
public function sanitise_preferences( $data ) {
Description: Method used to sanitize or setup hook settings after they have been saved by the user in the admin area.
Variable Type Required Description
data array Yes The hooks newly submitted settings.
}
public function field_name( $field = '' ) {
Description: Returns the hook settings field name. Should be used when displaying settings in the admin area. Ensures that field names are always correct.
Variable Type Required Description
field string or array Yes The field name.
}
public function field_id( $field = '' ) {
Description: Returns the hook settings field id. Should be used when displaying settings in the admin area. Ensures that field ids are always correct.
Variable Type Required Description
field string or array Yes The field id.
}
public function over_hook_limit( $instance = '', $reference = '', $user_id = NULL, $ref_id = NULL ) {
Description: Returns true if the hook limit has been reached (assuming one has been set), else it returns false.
Variable Type Required Description
instance string Yes The hook instance to check.
reference string Yes The reference to check.
user_id int Yes The user ID to check.
ref_id int No Optional reference ID to check.
}
public function get_limit_types() {
Description: Returns an array of options that can be selected in the hook limit settings dropdown.
Variable Type Required Description
No variables
}
public function hook_limit_setting( $name = '', $id = '', $selected = '' ) {
Description: Returns the hook limit settings. This method can only be used in the preferences() method for instances that needs to support limits.
Variable Type Required Description
name string Yes The settings name to use.
id string Yes The settings id to use.
selected string Yes The saved settings.
}
public function has_entry( $reference = NULL, $ref_id = NULL, $user_id = NULL, $data = NULL, $type = NULL ) {
Description: Checks if a specific log entry exists in the database.
Variable Type Required Description
reference string No The reference to check.
ref_id int No The reference id to check.
user_id int No The user id to check.
data string No The data to check for. If you know the data is an array, make sure this value is a serialized array.
type string No The point type to check.
}

Back To Top

myCRED_Lottery

Package: mycred/game Category: Classes

Navigation:

  1. Description
  2. Usage
  3. Properties
  4. Methods
  5. Lottery Parameters
  6. Usage Examples

Description

The myCRED_Lottery class handles all lottery related information. This class does not save any information to your database, it only retrieves and processes lottery details in order for you to be able to present or retrieve.

This class requires a lottery post ID to work and only handles one lottery at a time.

 

 

Usage

$lottery = new myCRED_Lottery( $lottery_id );

 

Properties

  • $id (int)
    Lottery post ID.
  • $post (object)
    The lottery post object.
  • $prefs (array)
    This lotteries preferences.
  • $state (string)
    The lotteries current state.
  • $mycred (array)
    The myCRED_Settings Object.

 

Methods

  1. myCRED_Lottery()Constructs the lottery class and populates the lottery’s ID, preferences and loads the myCRED_Settings object.

  2. lottery_exists()Checks if a lottery exists and if the lottery is found, the lottery post object is populated. If this method is not called, the post object is not populated!

  3. default_prefs()This method holds the default settings for lotteries. It is mainly used internally though this class to populate preferences. It’s main job is to make sure there are no missing settings.

  4. get_prefs()Returns the current lotteries preferences.

  5. get_type()Returns the lottery type which is stored as a post meta under ‘mycred_lottery_type’.

  6. get_schedule_prefs()Returns the lottery schedule settings.

  7. get_game_prefs()Returns the lottery game settings.

  8. get_participation_prefs()Returns the lottery participation settings.

  9. get_winnings_prefs()Returns the lottery winnings settings.

  10. get_jackpot_prefs()Returns the lottery jackpot settings.

  11. get_exclude_prefs()Returns the lottery exclude settings.

  12. get_requirements_prefs()Returns the lottery requirements settings.

  13. get_templates_prefs()Returns the lottery templates.

  14. get_state()Returns the lotteries state which is stored as a post meta under ‘mycred_lottery_status’.

  15. get_title()Returns the lottery post title.

  16. get_content()Returns the lottery post content.

  17. can_play( $user_id, $entries, $repeat )Checks if a user can play this lottery. Returns a string value.

    • $user_id (int) required
      The user id to check.
    • $entries (int) required
      The number of entries this user would like to enter. Defaults to 1.
    • $repeat (int) required
      The number of repeats that the user would like play (if allowed). Defaults to 1.

    Returned string values:

    • play – User can play
    • visitor – User is not logged in
    • closed – Lottery is closed
    • excluded – User is excluded
    • req – User does not meet minimum requirements
    • max – User has reached heir maximum number of entries in this lottery
    • insolvent – User can not afford to play
  18. is_excluded( $user_id )Checks if a user is excluded from playing according to the “Exclude” preferences. Returns true or false.

    • $user_id (int)
      The user ID to check.
  19. fail_requirements( $user_id )Checks if a user fails to reach the minimum requirements for this lottery. Returns to true or false.

    • $user_id (int)
      The user ID to check.
  20. max_entry( $user_id )Checks if a user has reached the maximum entries allowed for this lottery according to the “Participation” settings.

    • $user_id (int)
      The user ID to check.
  21. is_insolvent( $user_id, $entries, $repeat )Checks if a user has enough points to play the number of entries and repeats that is requested. Returns true or false.

    • $user_id (int) required
      The user id to check.
    • $entries (int) required
      The number of entries this user would like to enter. Defaults to 1.
    • $repeat (int) required
      The number of repeats that the user would like play (if allowed). Defaults to 1.
  22. get_entries( $users )Returns either all lottery entries or all users with entries in this lottery. Returns an associative array.

    • $users (bool)
      If set to true, an array of user ids are returned else if it is set to false, an associative array of user ids and entries are returned.
  23. get_total_users_playing()Returns the number of users that are playing this lottery.

  24. get_total_entries()Returns the total number of entries in this lottery.

  25. get_users_entries( $user_id )Returns a given users entries.

    • $user_id (int)
      The user ID.
  26. count_users_entries( $user_id )Returns the number of entries a user has in this lottery.

    • $user_id (int)
      The user ID to check.
  27. get_ticket( $entry )Converts an entry string into an assosiative array containing the entries values.

    • $entry (string)
      The entry string.
  28. get_current_ticket_id()Returns the latest lottery ticket ID.

  29. get_ticket_play( $ticket_id, $play )Returns the users play in this lottery. If the lottery is a draw winner type of lottery, the lottery ID is shown while in pick number lotteries, the users played number are returned.

    • $ticket_id (int)
      The ticket ID.
    • $play (string)
      The users play.
  30. get_ticket_run( $repeat )Returns the number of days / weeks a play will run based on the lottery schedule.

    • $repeat (int)
      The number a lottery entry is repeated.
  31. get_current_jackpot()Returns the current jackpot (if used).

  32. increment_current_jackpot()Returns the jackpot amount based on the current jackpot incremented according to the “Jackpot” settings.

 

Lottery Parameters

  • id (int)
    Required Lottery Post ID.

 

Usage Examples

Example 1: Get the lottery post object and echo the publishing date.

$lottery_id = 1;
$lottery = new myCRED_Lottery( $lottery_id );
if ( $lottery->lottery_exists() ) {
	echo 'This lottery was published on: ' . $lottery->post->post_date;
}
else {
	echo 'Lottery not found.';
}

Example 2: Check if the current user can play the lottery and if they can not, show the appropriate template for why not.

$user_id = get_current_user_id();
$lottery_id = 1;
$lottery = new myCRED_Lottery( $lottery_id );
$can_play = $lottery->can_play( $user_id );
// can_play() will return the string 'play' if user can play
if ( $can_play == 'play' ) {
	// user can play
}
else {
	// user can not play so we get all templates
	$templates = $lottery->get_templates_prefs();
	echo $templates[ $can_play ];
}

Back To Top

myCRED_Module

Package: mycred/core Category: Classes

Description

The myCRED_Module is an abstract class, responsible for constructing and supporting each myCRED Module via the Module API. It contains a set of commonly used functions to help you built modules with ease.

As an abstract class, your module must extend this class which will allow you to use any of the provided functions or replace them with your own.

Navigation

  1. Description
  2. Usage
  3. Properties
  4. Methods
  5. Module Arguments
  6. Examples

Usage

class My_Custom_Module extends myCRED_Module {
	function __construct( $point_type ) {
		parent::__construct( $module_id, $args, $point_type );
	}
}

Properties

  • $module_id (string)
    The unique module id. Important! Modules will fail and die if no module id is given!
  • $core (object)
    myCRED Settings.
  • $module_name (string)
    Required identifier for settings native to this module.
  • $option_id (string)
    Optional option ID this module uses.
  • $labels (array)
    Menu and Page Title labels. Only used if the module generates a sub page under the “myCRED” menu.
  • $register (boolean)
    Option to register module settings (if used). Defaults to false.
  • $screen_id (string)
    Screen ID for the module page (if used).
  • $menu_pos (int)
    Menu position.

Methods

  1. myCRED_Module( $module_id, $args )Constructs a module. If no module id is set this method will fail and die!
    • $module_id (string) required
      Constructs a module. If no module id is set this method will fail and die!.
    • $args (array)
      Module arguments.
  2. set_settings( $defaults )Populates the modules settings applying defaults if not set.
    • $defaults (array)
      Default settings.
  3. load()Hooks into myCRED. A module can overwrite this with it’s own load() method.
  4. module_pre_init()Runs before ‘init’.
  5. module_init()Runs at ‘init’.
  6. module_admin_init()Runs at ‘admin_init’.
  7. module_widgets_init()Runs at ‘widgets_init’.
  8. call( $call, $callback, $return )Either runs a given function or a class method. If $return is set, the value passed though it is passed on to the function/class method.
    • $call (string)
      Class method name to call. Ignored if function is called.
    • $callback (string)
      Function or Class to call.
    • $return (any)
      Optional value to pass on and return.
  9. add_menu()Adds a new sub menu item to the “myCRED” Admin Menu. Requires $labels and $screen_id to be set!
  10. register_settings()Registers a modules custom settings.
  11. settings_header()Outputs the “click to open” and “click to close” text to the accordion. Only used if the accordion is requested.
  12. admin_page()Outputs the admin page content. This method must be replaced by the custom module or an empty page is returned.
  13. sanitize_settings( $post )Used if the module has custom settings. This method must be replaced when used by the module and proper sanitation of the values must be made!
  14. after_general_settings()Option to insert custom content after the myCRED Core settings.
  15. sanitize_extra_settings( $new_data, $data, $core )If after_general_settings() is used, this method must be replaced by the custom module and sanitize the settings before they are saved into the DB. If not set, no settings are saved!
    • $new_data (array)
      The sanitized and correct data to save in the database.
    • $data (array)
      The initial posted data.
    • $core (object)
      myCRED Settings.

Module Arguments

// default
$args = array(
	'module_name' => '',
	'option_id'   => '',
	'defaults'    => array(),
	'labels'      => array(
		'menu'        => '',
		'page_title'  => ''
	),
	'register'    => true,
	'screen_id'   => '',
	'add_to_core' => false,
	'accordion'   => false,
	'menu_pos'    => 10
);
  • module_name (string)
    Module name used when modules add settings that can be accessed though myCRED_Settings.
  • option_id (string)
    Optional option id used by this module.
  • defaults (array)
    Default module settings.
  • labels (array)
    Array of labels when the module has it’s own admin page.
  • register (boolean)
    Option to register a modules settings though register_setting(). Should be set to true of option_id is set.
  • screen_id (string)
    A screen id if the module generates a custom admin page.
  • add_to_core (boolean)
    Option to add module settings to the myCRED Settings page. Defaults to false.
  • accordion (boolean)
    Option to include the Accordion script on the module page. Defaults to false.
  • menu_pos (int)
    Menu position.Default positions: Log (10), Hooks (20), Add-ons (30), Settings (99).

Examples

Example 1: A module which generates a new menu item between Log and Hooks called “Custom”.

class My_Custom_Module extends myCRED_Module {
	function __construct() {
		parent::__construct( 'My_Custom_Module', array(
			'module_name' => 'custom',
			'labels'      => array(
				'menu'        => __( 'Custom' ),      // Menu Label
				'page_title'  => __( 'Custom Page' )  // Page Title
			),
			'screen_id'   => 'myCRED_page_custom',
			'menu_pos'    => 15
		) );
	}

	function admin_page() {
		echo 'This is my custom page!';
	}
}

Example 2: A module which does not add a new page but instead adds new settings under myCred Settings.

class My_Custom_Module extends myCRED_Module {
	function __construct() {
		parent::__construct( 'My_Custom_Module', array(
			'module_name' => 'custom',
			'defaults'    => array(
				'foo'   => 1,
				'bar'   => ''
			),
			'register'    => false,
			'add_to_core' => true
		) );
	}

	// Output our settings or content
	function after_general_settings() {
		// We can access our custom settings under $this->$module_name
		$custom_settings = $this->custom;
		echo 'Custom settings output.';
	}

	// Sanitize our settings
	function sanitize_extra_settings( $new_data, $data, $core ) {
		// Our custom settings are found under $data[$module_name]
		$new_data['custom']['foo'] = sanitize_text_field( $data['custom']['foo'] );
		$new_data['custom']['bar'] = sanitize_text_field( $data['custom']['bar'] );
	}
}

Back To Top

myCRED_Payment_Gateway

Package: mycred/purchase Category: Classes

Navigation:

  1. Description
  2. Usage
  3. Properties
  4. Methods

Description

The myCRED_Payment_Gateway is a template class used by the BuyCred Add-on. It contains all the neccessery class methods along with a set of template functions.

Note! You should never initiate this class directly! Instead make sure your custom hook extends it (see usage example bellow).

Usage

class My_Custom_Gateway extends myCRED_Payment_Gateway {
	function __construct( $gateway_prefs ) {
		parent::__construct( $args, $gateway_prefs );
	}
}

Properties

  • $id (string)
    Gateway ID.
  • $core (object)
    myCRED Settings.
  • $prefs (array)
    This gateways preferences.
  • $current_user_id (int)
    The current users id (if logged in).
  • $response (string)
    Responses from the gateway or via the execution of the gateway. It can for example hold information when an error occurs.
  • $request (array)
    The purchase request being sent to the gateway to process.
  • $status (int|string)
    Payment status.
  • $errors (array)
    Holds (if any) error objects.

Methods

  1. myCRED_Payment_Gateway()Class constructor populating $current_user_id, $args, $prefs and $core.
  2. process()This method must be replaced by the child class and should manage requests from either form submissions resulting in contacting a payment gateway or by incoming notifications/verifications from a gateway.
  3. buy()This method must be replaced by the child class and should manage requests made to purchase creds. All purchase requests must nominate the gateway to avoid multiple gateway attempting to process the same purchase.
  4. returning()This method must be replaced by the child class if a purchase request were processed remotely.
  5. preferences()Outputs the gateways preferences. If not set, the default “This Gateway has no settings” is shown.
  6. sanitise_preferences( $data )Option to sanitize the gateways settings before they are saved in the database.
    • $data (array)
      The posted data.
  7. field_name( $data )Outputs this gateways field name.
    • $data (string|array)
      Either a string with the field id or an array if hook has multiple settings.
  8. field_id( $data )Outputs this gateways field id.
    • $data (string|array)
      Either a string with the field id or an array if hook has multiple settings.
  9. decode_log_entries( $entry, $object )This method decodes the log entry for purchases. When purchases are made, the buyers ID is saved under ref_id allowing us to use this users data as template tags.
    • $entry (type)
      The log entry.
    • $object (type)
      The log object.
  10. callback_url()Returns the callback URL for this gateway. Used by PayPal as the URL for the IPN callback. Can be used by any gateway that requires a callback URL.
  11. purchase_header( $title, $reload )Purchase page header.
  12. purchase_footer()The purchase page’s footer.
  13. form_with_redirect( $hidden_fields, $location, $logo_url, $custom_html, $sales_data )Generates a purchase form with the given hidden fields along with a gateway logo and optional custom html. Used by gateways with remote processors (i.e. PayPal or Skrill).
    • $hidden_fields (array)
      Required hidden form fields needed by the gateway.
    • $location (string)
      Form action URL.
    • $logo_url (string)
      Optional gateway logo URL.
    • $custom_html (string)
      Optional HTML to insert in page.
    • $sales_data (string|array)
      Optional sales data to include in page.
  14. get_to()Returns either the current user id or if gifting is enabled and used the id of the user this is gifted to.
  15. get_thankyou()Returns the “Thank You” page URL.
  16. get_cancelled()Returns the “Cancelled” page URL.
  17. get_entry( $_to, $_from )Returns the appropriate log entry template. If “Gifting” is enabled and the two values do not match the gift template is returned.
    • $_to (int)
      The user id of the recipient.
    • $_from (int)
      The user id of the purchaser.
  18. POST_to_data( $unset )Converts posted variables to local with the option to unset $_POST once done.
    • $unset (bool)
      Option to unser $_POST before returning the variables.
  19. transaction_id_is_unique( $transaction_id )Searches the log for a given transaction id. Returns false if id was found else true. Used to make sure purchases are unique.
    • $transaction_id (string|int) required
      The transaction id to look for.
  20. create_token()Returns a WP Nonce for the purchase. Uses wp_create_nonce().
  21. verify_token( $user_id, $nonce )Based on wp_verify_nonce() with the difference that a user id must be given. Returns true or false.
    • $user_id (type) required
      User id for the nonce in question.
    • $nonce (type) required
      The nonce.
  22. encode_sales_data( $data )Encodes the sales data. Uses the myCRED_Protect() class.
    • $data (string) required
      The data to be encoded.
  23. decode_sales_data( $data )Decodes the sales data. Uses the myCRED_Protect() class.
    • $data (string) required
      The data to be decoded.
  24. currencies_dropdown( $name )Generates a drop-down menu with accepted currencies. Uses the ‘mycred_dropdown_currencies’ filter.
    • $name (string) required
      The drop-down elements name.
  25. item_types_dropdown( $name )Generates a drop-down menu with available item types. Used by PayPal. Uses the ‘mycred_dropdown_item_types’ filter.
    • $name (string) required
      description.
  26. list_option_countries( $selected )Echos a list of html options for nations, highlighting the selected. Uses the ‘mycred_list_option_countries’ filter.
    • $selected (string)
      The selected countries two letter code.
  27. list_option_us_states( $selected, $non_us )Echos a list of html options for US states. If $non_us is set to true the “Outside US” option is appended.
    • $selected (string)
      The selected states two letter abbreviation.
    • $non_us (boolean)
      Option to add “Outside US”.
  28. list_option_months( $selected )Echos a list of html options for each month.
    • $selected (int) required
      The selected month number with leading zero.
  29. list_option_card_years( $selected, $number )Echos a list of html options for credit card expiry years.
    • $selected (type) required
      The selected years last two digits.
    • $number (type) required
      The number of years into the future to generate. Defaults to 16.

Back To Top

myCRED_Query_Log

Package: mycred/log Category: Classes
Description

This class allows you to search the myCRED Log for entries based on a large variety of options. Similar to the WP_Query class, you can use this class to query and then loop through the results in order to show the results in any way you like. Currently the class also has a large set of functions to help you render a table where these results are presented. This feature is currently used by the Log module in your admin area and by the mycred_history shortcode / widget.

In version 1.8, this class will be split up and focus on running queries in the database while a separate class will be made available that will render the table to show the results.

This documentation is for version 1.7 or later which was introduced in myCRED 1.7.5.

Interacting with the Class

While the class offers a large number of functions for you to use, your most common interaction will be with constructing and providing arguments for your search.

// Example 1: Show the last 10 entries
$args = array(
	'number' => 10
);

// The Query
$log = new myCRED_Query_Log( $args );

// The Loop
if ( $log->have_entries() ) {

	// Display using the built-in table
	$log->display();

}
// Example 2: Get log entries for user 1
$args = array(
	'user_id' => 1
);

// The Query
$log = new myCRED_Query_Log( $args );

// The Loop
if ( $log->have_entries() ) {

	// Build your custom loop
	foreach ( $log->results as $entry ) {

		// Present the results anyway you like

	}

}
Class Properties
Property Declared Type Description
$now Public int The current unix timestamp. Used for date / time rendering and parsing.
$render_mode Public bool Indicates if the class allows results to be rendered using the built-in methods or if only queries can be made. Added in 1.7.5
$args Public array Holds the arguments that the class was constructed around.
$request Public string The SQL query that was run to get the results you are seeing.
$num_rows Public int The number of rows the query returned.
$max_num_pages Public string The maximum number of pages the results span over. Defaults to 1.
$total_rows Public int The total number of rows in the database.
$results Public array The results of your query.
$headers Public array Holds an associative array of headers that the table will render.
$hidden_headers Public array Holds an array of header ids that you have selected to hide.
$core Public object The myCRED_Settings class object.
$is_admin Public bool Indicates if the class is used in the front end or in the wp-admin area.
$references Public array An array of reference IDs and their labels. This is used to translate each log entries reference when displayed in the table.
$refs Public array An array containing all references that exists in the database, based on the current query. Added in 1.7.5
$types Public array Populated with the myCRED_Settings object for each point type we are searching for. This is used when you are rendering a table for the query results with multiple point types. Added in 1.7.5
Class Parameters

The class has only two parameters that you can use.

Parameter Type Required Description
$args array Yes The query arguments to return results for.
$array bool No Option to return entries in an array format instead of object format. Can not be used when the fields argument is set to return a specific column.
Query Arguments

Arguments can be passed in string or array format. When using a string format, you separate each argument with an & character. String format is well suited in simple straightforward queries, however for more advanced queries, an array format is required.

Entry IDs

Argument Type Description
entry_id array or int Retrieve log entries based on their unique ids. Supports queries of a single id or multiple ids. Supports =, !=, IN and NOT IN comparisons.

Example 1: Get a single entry that has the id 1

$log = new myCRED_Query_Log( 'entry_id=1' );

Example 2: Get multiple entries

$log = new myCRED_Query_Log( array( 'entry_id' => array( 1, 2, 3 ) );

Example 3: Get entries that does not have the ids 1 or 2

$args = array(
	'entry_id' => array(
		'ids'     => array( 1, 2 ),
		'compare' => 'NOT IN'
	)
);
$log  = new myCRED_Query_Log( $args );

Example 4: Get entries that does not have the id 5

$args = array(
	'entry_id' => array(
		'ids'     => 5,
		'compare' => '!='
	)
);
$log  = new myCRED_Query_Log( $args );

Point Types

Argument Type Description
ctype array or string Retrieve log entries of a particular point type or multiple types based on the point type key. Supports =, !=, IN and NOT IN comparisons.

If this argument is not set, the class will set it to show entries of the main point type. To show entries no matter which point type they belong to, make sure you set this attribute to an empty string.

Example 1: Get entries of the default point type

$log = new myCRED_Query_Log( 'ctype=mycred_default' );

Example 2: Get entries of a custom point type

$log = new myCRED_Query_Log( array( 'ctype' => 'mycustom_type' ) );

Example 3: Get entries that are not of a custom point type

$args = array(
	'ctype' => array(
		'ids'     => array( 'mycustom_type', 'anothertype' ),
		'compare' => 'NOT IN'
	)
);
$log  = new myCRED_Query_Log( $args );

Example 4: Get entries of all point types

$log = new myCRED_Query_Log( array( 'ctype' => '' ) );

User IDs

Argument Type Description
user_id array or int Retrieve log entries one or multiple users based on their numeric IDs. Supports =, !=, IN and NOT IN comparisons.

If you do not know the users numeric ID, you can always use the mycred_get_user_id function which supports converting usernames, email addresses or slugs into numeric IDs (assuming a user is found to match).

Example 1: Get entries for the user with the ID 1

$log = new myCRED_Query_Log( 'user_id=1' );

Example 2: Get entries for a set of users

$log = new myCRED_Query_Log( array( 'user_id' => array( 1, 2, 4 ) ) );

Example 3: Get entries that do not belong to users 1, 2 and 6

$args = array(
	'user_id' => array(
		'ids'     => array( 1, 2, 6 ),
		'compare' => 'NOT IN'
	)
);
$log  = new myCRED_Query_Log( $args );

References

Argument Type Description
ref array or string Retrieve log entries based on one or multiple references. Supports =, !=, IN and NOT IN comparisons.

Example 1: Get all manual entries

$log = new myCRED_Query_Log( 'ref=manual' );

Example 2: Get entries for approved comments and published content

$log = new myCRED_Query_Log( array( 'ref' => array( 'approved_comment', 'published_content' ) ) );

Example 3: Get all entries that are not manual

$args = array(
	'ref' => array(
		'ids'     => 'manual',
		'compare' => '!='
	)
);
$log  = new myCRED_Query_Log( $args );

Example 4: Get all entries of a custom reference

$args = array(
	'ref' => array(
		'ids'     => 'mycustomreference',
		'compare' => '='
	)
);
$log  = new myCRED_Query_Log( $args );

Reference IDs

Argument Type Description
ref_id array or int Retrieve log entries based on one or multiple reference IDs. Supports =, !=, <, <=, >=, IN and NOT IN comparisons.

Example 1: Get all entries with the reference id 1

$log = new myCRED_Query_Log( 'ref_id=1' );

Example 2: Get entries with a reference id of 1, 2 or 3

$log = new myCRED_Query_Log( array( 'ref_id' => array( 1, 2, 3 ) ) );

Example 3: Get all entries with a reference id lower than 100

$args = array(
	'ref_id' => array(
		'ids'     => 100,
		'compare' => '<'
	)
);
$log  = new myCRED_Query_Log( $args );

Example 4: Get all entries that have a reference id higher or equal to 10, no matter which point type the entry belongs to

$args = array(
	'ref_id' => array(
		'ids'     => 10,
		'compare' => '>='
	),
	'ctype' => ''
);
$log  = new myCRED_Query_Log( $args );

Point Amounts

Argument Type Description
amount array or int or float Retrieve log entries based on one or multiple amounts. Supports =, !=, <, <=, >=, BETWEEN, NOT BETWEEN, IN and NOT IN comparisons.

Example 1: Get all entries were users gained 1000 points

$log = new myCRED_Query_Log( 'amount=1000' );

Example 2: Get entries where a user gained 10, 20 or 50 points

$log = new myCRED_Query_Log( array( 'amount' => array( 10, 20, 50 ) ) );

Example 3: Get all entries where a user has gained between 0 and 100 points

$args = array(
	'amount' => array(
		'num'     => array( 0, 100 ),
		'compare' => 'BETWEEN'
	)
);
$log  = new myCRED_Query_Log( $args );

Example 4: Get all entries where a user lost points, no matter which point type

$args = array(
	'amount' => array(
		'num'     => 0,
		'compare' => '<'
	),
	'ctype' => ''
);
$log  = new myCRED_Query_Log( $args );

Time

Argument Type Description
time array or int or string Retrieve log entries for a given time period or date/time. You can supply a well formatted date/time string, a unix timestamp or a keyword. Supported keywords: today, yesterday, thisweek and thismonth. Supports =, !=, <, <=, >=, BETWEEN, NOT BETWEEN, IN and NOT IN comparisons.

myCRED stores dates in unix timestamp format. If you do not provide a unix timestamp, the class will use strtotime to convert your given date/time into a unix timestamp. This allows you to to use keywords that strtotime accepts along with dates/times.

If you provide a date but not a time, the class will query entries up until the end of the day and not the beginning of the day! If this is not desired, make sure you also include a time with your date.

Example 1: Get todays entries

$log = new myCRED_Query_Log( 'time=today' );

Example 2: Get all entries for a specific date

$log = new myCRED_Query_Log( array( 'time' => '2016-10-01' ) );

Example 3: Get all entries between two dates

$args = array(
	'time' => array(
		'dates'   => array( '2016-01-01 00:00:01', '2016-12-31 23:59:59' ),
		'compare' => 'BETWEEN'
	)
);
$log  = new myCRED_Query_Log( $args );

Example 4: Get all entries before the start of today

$args = array(
	'time' => array(
		'dates'   => 'today midnight',
		'compare' => '<'
	)
);
$log  = new myCRED_Query_Log( $args );

Searching

Argument Type Description
s int or string Search the "entry" columns and retrieve entries that match. You can use wildcards % for LIKE comparisons.
data int or string Search the "data" columns and retrieve entries that match. You can use wildcards % for LIKE comparisons.

As of version 1.7.5, no wildcards are added to the search string automatically. Instead you are required to add them in. If no wildcards are used, the class will search the value exactly.

Example 1: Get entries that has the string “boo“ in their description

$log = new myCRED_Query_Log( 's=boo' );

Example 2: Get entries where the “entry“ columns content starts with “Tokens“

$log = new myCRED_Query_Log( array( 's' => 'Tokens%' ) );

Example 3: Get entries that has the string “boo“ in their data column

$log = new myCRED_Query_Log( 'data=boo' );

Example 4: Get entries where the “data“ columns content a serialized array

$log = new myCRED_Query_Log( array( 'data' => 'a:1:{s:8:"ref_type";s:4:"user";}' ) );

Sorting of Results

Argument Type Description
orderby array or string Sort the retrieved log entries. As of version 1.7.5 you can sort by multiple columns by providing an array of columns and their order.
order string Either ASC for ascending or DESC for descending. Ignored if orderby is an array.

Example 1: Get entries for the user 1 ordered by time in an ascending order (latest entry is shown last)

$args = array(
	'user_id' => 1,
	'orderby' => 'time',
	'order'   => 'ASC'
);
$log  = new myCRED_Query_Log( $args );

Example 2: Get “Manual“ entries sorted by the point amount (largest first), then by time

$args = array(
	'ref'     => 'manual',
	'orderby' => array( 'creds' => 'DESC', 'time' => 'DESC' )
);
$log  = new myCRED_Query_Log( $args );

Return Fields

Argument Type Description
fields array or string Either the name of a particular column or an array of column names you want returned in your results. See the log structure documentation for accepted values.
ids bool Option to only return the log entries unique ID. Depreciated since 1.7.5 and will be removed in future versions in favour for fields.

The fields argument was introduced in version 1.7.5 and is not available on older versions! If you use this argument, you will not have access to the table rendering methods in this class as these methods were built to show results from all columns and not just some / one. If used, the $render_mode Parameter will switch to FALSE.

Example 1: Get the log entry ids only for a specific user

$args = array(
	'user_id' => 1,
	'fields'  => 'id'
);
$log  = new myCRED_Query_Log( $args );

Example 2: Get the log entry ids and the point amounts only for a specific user

$args = array(
	'user_id' => 5,
	'fields'  => array( 'id', 'creds' )
);
$log  = new myCRED_Query_Log( $args );

Pagination

Argument Type Description
number int The number of entries to return. By default this is 25. Use -1 to return all entries. If you are rendering the results in the class table, this will be the number of entries shown per page.
paged int The page number. Retrieve entries that would show on page x when using the navigation. Defaults to 1 as in the first page.
offset int Number of entries to displace or pass over. Should be used in combination with number. Defaults to zero.

It is not recommended to show all log entries when you intend to render then in the class table! If you do, the page will load slower and slower as the number of entries increase!

Example 1: Show 15 entries per page

$args = array(
	'user_id' => 1,
	'number'  => 15
);
$log  = new myCRED_Query_Log( $args );

Example 2: Get all manual log entries

$args = array(
	'ref'    => 'manual',
	'number' => -1
);
$log  = new myCRED_Query_Log( $args );
Query Filters

Your query will trigger the following filters whenever the class is constructed:

Filter Description
mycred_query_log_args Allows you to manipulate the query arguments before it is processed by the class.
mycred_allowed_sortby Controls what values the query can be sorted by. By default this is the log column headers.

Back To Top

myCRED_Remote

Package: mycred/api Category: Classes

Navigation:

  1. Description
  2. Supported Actions
  3. Properties
  4. Methods
  5. Error Messages

Description

This is the main myCRED API class allowing your site to award / deduct points based on requests from other websites. Just like everything else in myCRED, this class is pluggable and can be replaced / altered. There are also several actions and filters associated with this class allowing further customizations / expansion.

Requires myCRED 1.3 or higher.

 

Supported Actions

  • CREDIT
    Add points to a specific user.
  • DEBIT
    Deduct points from a specific user.
  • GET
    Get the current balance of a specific user.
  • PAY
    Deduct points from one user and credit the amount deducted to another user.

 

Supported Methods

  • JSON
  • _GET
  • _POST

If you are looking to create call scripts to interact with this class, please consider using the wp_remote_get or wp_remote_post WordPress functions.

 

Properties

  • $method (string)
    The method used for the incoming API call.
  • $uri (array)
    The $_SERVER[‘REQUEST_URI’] value in an array format.
  • $request (array)
    The API call request array.
  • $host (string)
    The remote callers IP address.
  • $format (string)
    The format of the API call.
  • $user (object)
    The requested user object.
  • $recipient (object)
    The requested recipient user object. Only used for transfers.
  • $reply (string)
    The reply sent back once the call has been processed. Defaults to ‘PROCESSING’. See the error list for a complete list of possible replies.
  • $core (object)
    The myCRED_Settings object.
  • $key (string)
    The API Key.

 

Methods

  1. myCRED_Remote( $key )Handles magic quotes, populates $method, $uri, $format, $host and $core. Requires the API key.

    Action: mycred_remote (ref array)

  2. handle_magic()Handles magic quotes for $_GET, $_POST, $_COOKIE and $_REQUEST.

    Action: mycred_remote_magic(ref array)

  3. set_headers()Sets the API reply headers.

    Action: mycred_remote_headers (ref array)

  4. parse_call()Parses the API call to determine how the API call is made. Supports JSON or HTML. Populates $request and $format.

    Action: mycred_remote_parse (ref array)

  5. get_host_IP()Retreaves the IP address of the caller.

    Action: mycred_remote_host_IP (ref array)

  6. validate_call()Validates the API call. This method either returns an error message or true if the call passes validation.

    Action: mycred_remote_validate (ref array)
    Returns: True (bool) or an error code (string).

  7. process()The main API processor. Processes the API request and returns a string reply. Possible values:

    Filter: mycred_transfer_acc_limit
    Action: mycred_remote_process (ref array)
    Action: mycred_remote_process_{$action} (ref array)
    Returns: The process result (string).

    • COMPLETEDThe request has been successfully completed.
    • FAILEDThe request failed.
    • DUPLICATEThe request is deemed to be a duplicate and was rejected.
    • DECLINEDThe request was declined due to insufficient funds.
    • UNKNOWNUnknown / unsupported request.

 

Error Messages

Important! The following error messages is only available if you have enabled “Debug Mode”. It is very important to disable “Debug Mode” once you are done testing / developing to prevent mischievous calls from learning about your setup!

  1. 0 – 100 Plugin related issues.

    • ERROR: 99 The API Key has not been set or is empty.
  2. 100 – 199 API Call related issues.

    • ERROR: 101 The request is empty.
    • ERROR: 102 The required “action” key is missing or empty in the request.
    • ERROR: 103 The required “account” key is missing or empty in the request.
    • ERROR: 104 The required “token” key is missing or empty in the request.
    • ERROR: 105 The required “host” key is missing or empty in the request.
  3. 200 – 299 User related issues.

    • ERROR: 201 The user count not be found. Remember that the API only supports users identified via an email address.
    • ERROR: 202 The user is excluded from using myCRED.
  4. 300 – 399 Request specific issues regardless of what action is requested.

    • ERROR: 301 Invalid security token.
    • ERROR: 302 Unknown / Unsupported Action request.
  5. 400 – 499 CREDIT & DEBIT related issues.

    • ERROR: 401 The required “ref” key is missing or empty in the request.
    • ERROR: 402 The required “entry” key is missing or empty in the request.
    • ERROR: 403 The required “amount” key is missing or empty in the request.
  6. 500 – 599 GET related issues.

    • none
  7. 600 – 699 PAY related issues.

    • ERROR: 501 The required “ref” key is missing or empty in the request.
    • ERROR: 502 The required “entry” key is missing or empty in the request.
    • ERROR: 503 The required “amount” key is missing or empty in the request.
    • ERROR: 504 The required “to” key is missing or empty in the request.
    • ERROR: 505 The required “data” key is missing or empty in the request.
    • ERROR: 506 The recipient user could not be found.
    • ERROR: 507 The recipient user ID is the same as the sender.
    • ERROR: 508 The recipient user has been excluded from using myCRED.

Back To Top

myCRED_Settings

Package: mycred/core Category: Classes
Description

This class constructs and enables a set of core tools that allows you to execute point related actions or retrieve points related details.

Multiple point type support was added in version 1.4. Older versions of this class differ significantly and are no longer supported!

Available since version 1.0

Interacting with the Class

While the class can be called directly, it is highly recommended that you instead use the mycred function.

// Default usage
$mycred = mycred();

// Setup for a custom point type
$mycred = mycred( 'customtypekey' );
Class Properties
Property Declared Type Description
$core Public array The settings array for the current point type.
$log_table Public string The database table name based on your Network settings (if you use Multisite).
$cred_id Public string The meta key ID of the current point type.
$is_multisite Public bool The value of the is_multisite function.
$use_master_template Public bool True if the master template feature is enabled. False if not using multisite.
$use_central_logging Public bool True if the central logging is enabled. False if not using multisite.
Class Parameters

The class has only one parameter that can be used.

Parameter Type Required Description
$typekey string No The point type key to construct.
Class Methods

While you can interact with balances without using this class, the methods offered here will make sure your interaction happens faster and safer. Using these methods also ensures that you always have access to all point related features in myCRED.

public function defaults() {
Description: Returns the default settings array which is used when compiling the point type's settings.
Variable Type Required Description
No variables
}
public function singular() {
Description: Returns the current point types name in singular form.
Variable Type Required Description
No variables
}

Example 1: Display the point types given name in singular form

$mycred = mycred();

echo $mycred->singular();
public function plural() {
Description: Returns the current point types name in plural form.
Variable Type Required Description
No variables
}

Example 1: Display the point types given name in plural form

$mycred = mycred();

echo $mycred->plural();
public function zero() {
Description: Returns zero formatted according to the point type setup.
Variable Type Required Description
No variables
}
public function number( $number = '' ) {
Description: Returns the given value formatted according to the point types setup. Should be used when points are used in calculations.
Variable Type Required Description
number int or float Yes The value to format.
}
public function format_number( $number = '' ) {
Description: Returns a given value formatted based on the point types settings as a string. Should be used when points are intended to be displayed and not used in calculations.
Variable Type Required Description
number int or float Yes The value to format.
}
public function format_creds( $creds = 0, $before = '', $after = '', $force_in = false ) {
Description: Returns a given value formatted based on the point types settings with prefix / suffix added (if used). Can not be used in calculations!
Variable Type Required Description
creds int or float Yes The value to format.
before string No Optional string to attach before the formatted point value. If you use a prefix, this string is appended before the prefix.
after string No Optional string to attach after the formatted point value. If you use a suffix, this string is appended after the suffix.
force_in bool No Option to force the $before or $after variables before / after the prefix / suffix.
}

Example 1: Display a users balance formatted with a prefix / suffix (if used)

$mycred  = mycred();
$balance = $mycred->get_users_balance( get_current_user_id() );

echo $mycred->format_creds( $balance );
public function round_value( $amount = 0, $up_down = false, $precision = 0 ) {
Description: Rounds a given value either up or down with an option to set the precision.
Variable Type Required Description
amount int or float Yes The value to round.
up_down string Yes Either "up" to round up or "down" to round down.
precision int No Rounding precision. Defaults to zero.
}
public function get_lowest_value() {
Description: Returns the lowest possible points value above zero based on the point type setup. A point type setup that does not uses any decimals would return 1 while a point type using for example 2 decimal places would return 0.01. Mainly used to prevent users from sending partial points.
Variable Type Required Description
No variables
}
public function apply_exchange_rate( $amount = 0, $rate = 1, $round = true ) {
Description: Divides the amount by the given rate.
Variable Type Required Description
amount int or float Yes The initial point amount.
rate int or float Yes The exchange rate that are applied to the amount.
round bool No Option to round the value. Uses PHP round.
}
public function parse_template_tags( $content = '', $log_entry ) {
Description: Parses template tags in a given string. Can only be used when a log entry object is available. Based on the data column details, this method loads the appropriate template tag processor (see below).
Variable Type Required Description
content string Yes The string that potentially contain template tags.
log_entry object Yes The log entry object.
}
public function template_tags_general( $content = '' ) {
Description: Converts general template tags into their appropriate values.
Variable Type Required Description
content string Yes The string that potentially contain template tags.
}
public function template_tags_amount( $content = '', $amount = 0 ) {
Description: Converts amount related template tags into their appropriate values. Uses template_tags_general().
Variable Type Required Description
content string Yes The string that potentially contain template tags.
amount int or float Yes The amount to use when replacing amount related template tags.
}
public function template_tags_post( $content = '', $ref_id = NULL, $data = '' ) {
Description: Converts post related template tags into their appropriate values. Uses template_tags_general().
Variable Type Required Description
content string Yes The string that potentially contain template tags.
ref_id int Yes The reference ID stored with the log entry, usually the post object ID.
data string or array No The data stored with the log entry. Mainly used when a post has been deleted as the old past data is stored in the data column.
}
public function template_tags_user( $content = '', $ref_id = NULL, $data = '' ) {
Description: Converts user related template tags into their appropriate values. Uses template_tags_general().
Variable Type Required Description
content string Yes The string that potentially contain template tags.
ref_id int Yes The reference ID stored with the log entry, usually the user object ID.
data string or array No The data stored with the log entry.
}
public function template_tags_comment( $content = '', $ref_id = NULL, $data = '' ) {
Description: Converts comment related template tags into their appropriate values. Uses template_tags_general().
Variable Type Required Description
content string Yes The string that potentially contain template tags.
ref_id int Yes The reference ID stored with the log entry, usually the comment object ID.
data string or array No The data stored with the log entry.
}
public function has_tags( $type = '', $tags = '', $content = '' ) {
Description: Checks if a given string contains any template tags based on a set type e.g. comment, post or user. Returns true or false.
Variable Type Required Description
type string Yes The template tag type.
tags string Yes List of template tags to check for. This list is passed on to preg_match so if more then one tag needs to be checked for, this must be separated with a horizontal line |.
content string Yes The content string that needs to be checked.
}
public function available_template_tags( $available = array(), $custom = '' ) {
Description: Returns a string indicating the available template tags that can be used.
Variable Type Required Description
available array Yes An array or template tag types. These will be listed after the sentence: Available Template Tags:.
custom string No Optional list of additional / special template tags that are appended at the end of the string.
}
public function allowed_tags( $data = '', $allow = '' ) {
Description: Strips HTML tags of a given string based on the allowed html tags list provided by the allowed_html_tags method.
Variable Type Required Description
data string Yes The string that contains HTML tags that needs to be stripped.
allow array or bool No Either false to strip all tags, an array or allowed HTML tags not to strip of or if left empty, a default set of tags are removed.
}
public function edit_creds_cap() {
Description: Returns the capability set for point editors.
Variable Type Required Description
No variables
}

Example 1: Make sure the current user is a point editor.

$mycred = mycred();

// If the current user is a "point editor"
if ( current_user_can( $mycred->edit_creds_cap() ) ) {

}
public function can_edit_creds( $user_id = '' ) {
Description: Checks if a given user is a "point editor" based on the current point type. Uses user_can.
Variable Type Required Description
user_id int Yes The user ID to check.
}
public function edit_plugin_cap() {
Description: Returns the capability set for point administrators.
Variable Type Required Description
No variables
}

Example 1: Make sure the current user is a point editor.

$mycred = mycred();

// If the current user is a "point administrator"
if ( current_user_can( $mycred->edit_plugin_cap() ) ) {

}
public function can_edit_plugin( $user_id = '' ) {
Description: Checks if a given user is a "point administrator" based on the current point type. Uses user_can.
Variable Type Required Description
user_id int Yes The user ID to check.
}
public function in_exclude_list( $user_id = '' ) {
Description: Checks if a given user is in the list of excluded users. The ID is checked against the comma separated list of IDs you might have set to the current point type.
Variable Type Required Description
user_id int Yes The user ID to check.
}
public function exclude_plugin_editors() {
Description: Checks if the current point type has been set to exclude "point administrators". Returns true or false.
Variable Type Required Description
No variables
}
public function exclude_creds_editors() {
Description: Checks if the current point type has been set to exclude "point editors". Returns true or false.
Variable Type Required Description
No variables
}
public function exclude_user( $user_id = NULL ) {
Description: Checks if the given user is excluded from the current point type.
Variable Type Required Description
user_id int Yes The user object ID.
}

Example 1: Check if the current user is excluded from using the current point type.

$user_id = get_current_user_id();
$mycred  = mycred();

if ( ! $mycred->exclude_user( $user_id ) ) {

	// User is not excluded

}
public function count_members() {
Description: Returns the total number of users with a balance of the current point type.
Variable Type Required Description
No variables
}
public function get_cred_id() {
Description: Returns ID of the current point type.
Variable Type Required Description
No variables
}
public function max() {
Description: Returns the highest value allowed for the current point type.
Variable Type Required Description
No variables
}
public function get_users_balance( $user_id = NULL, $type = NULL ) {
Description: Returns the given users current balance for either a given point type or the current point type.
Variable Type Required Description
user_id int Yes The users numeric ID.
type string No Option to retrieve a users balance for a different point type then the current one. If you are want the current point types balance then this should not be used.
}

Example 1: Get the current users balance for the current point type

$user_id = get_current_user_id();
$mycred  = mycred();
$balance = 0;

// Get the balance if the user is not excluded
if ( ! $mycred->exclude_user( $user_id ) )
	$balance = $mycred->get_users_balance( $user_id );

It is highly recommended that you always check if a user is excluded before attempting to get their balance or before you introduce the user to balance related features. You might not be excluding a user right now but might do so at a later stage.

public function update_users_balance( $user_id = NULL, $amount = NULL, $type = NULL ) {
Description: Updates a given users points balance by a given value. This value can be positive to increase a users balance or negative to reduce a balance.
Variable Type Required Description
user_id int Yes The users numeric ID.
amount int or float Yes The point amount to adjust the balance with. This value must be properly formatted. If the point type does not use decimals, then the amount can not use decimals either.
type string No Option to update a different point balance then the current point type.
}

Example 1: Add 10 points to the current users balance.

$user_id = get_current_user_id();
$mycred  = mycred();
$amount  = 10;

// Update the balance if the user is not excluded
if ( ! $mycred->exclude_user( $user_id ) )
	$mycred->update_users_balance( $user_id, $amount );

Example 2: Deduct 50 points to the current users balance.

$user_id = get_current_user_id();
$mycred  = mycred();
$amount  = -50;

// Update the balance if the user is not excluded
if ( ! $mycred->exclude_user( $user_id ) )
	$mycred->update_users_balance( $user_id, $amount );

This method does not check if the user you are adjusting the balance for is excluded or not! This needs to be done before using this method.

public function set_users_balance( $user_id = NULL, $new_balance = NULL ) {
Description: Changes a users balance to the given value. Added in 1.7.3. Can only be used for the current point type.
Variable Type Required Description
user_id int Yes The users numeric ID.
new_balance int or float Yes The point amount to adjust the balance with. This value must be properly formatted. If the point type does not use decimals, then the amount can not use decimals either.
}

Example 1: Change the current users balance to 100 points.

$user_id     = get_current_user_id();
$mycred      = mycred();
$new_balance = 100;

// Update the balance if the user is not excluded
if ( ! $mycred->exclude_user( $user_id ) )
	$mycred->set_users_balance( $user_id, $new_balance );
public function add_creds( $ref = '', $user_id = '', $amount = '', $entry = '', $ref_id = '', $data = '', $type = MYCRED_DEFAULT_TYPE_KEY ) {
Description: Adds or deducts points from a given users account and saves a log entry of the transaction. Contrarily to what the name suggests, this method can be used to adding points as well as deducting points.
Variable Type Required Description
ref string Yes The reference to log the transaction under.
user_id int Yes The users numeric ID.
amount int or float Yes The point amount to adjust the balance with. This value must be properly formatted. If the point type does not use decimals, then the amount can not use decimals either.
entry string Yes The log entry of the transaction. This is what is shown to users in the logs.
ref_id int No Optional reference ID to save with the log entry.
data string or array No Optional data to save with the log entry. This can be a string or an array. Note that arrays will be serialized before saved to the log.
type string No The point type to adjust and log the transaction under. Should only be used if the point type is not the current point type set in this class.
}

Example 1: Give a user 10 points and log it as a “Donation“.

$user_id = 1;
$amount  = 10;
$mycred  = mycred();

if ( ! $mycred->exclude_user( $user_id ) )
	$mycred->add_creds(
		'donation',
		$user_id,
		$amount,
		'%plural% donation'
	);
public function add_to_log( $ref = '', $user_id = '', $amount = '', $entry = '', $ref_id = '', $data = '', $type = MYCRED_DEFAULT_TYPE_KEY ) {
Description: Adds a log entry to the myCRED Log database table. Used by add_creds().
Variable Type Required Description
ref string Yes The reference to log the transaction under.
user_id int Yes The users numeric ID.
amount int or float Yes The point amount. If the point type does not use decimals, then the amount can not use decimals either.
entry string Yes The log entry of the transaction.
ref_id int No Optional reference ID to save with the log entry.
data string or array No Optional data to save with the log entry. This can be a string or an array. Note that arrays will be serialized before saved to the log.
type string No The point type to adjust and log the transaction under. Should only be used if the point type is not the current point type set in this class.
}
public function update_log_entry( $entry_id = NULL, $data = array(), $prep = array() ) {
Description: Updates a given log entry. Requires that you have the log entries ID. Added in 1.6.7
Variable Type Required Description
entry_id int Yes The unique log entry ID.
data array Yes An array of new data. Uses the $wpdb->update().
prep array Yes An array of formats to be mapped to each of the values in $data..
}
public function has_entry( $reference = NULL, $ref_id = NULL, $user_id = NULL, $data = NULL, $type = NULL ) {
Description: Checks if a specific log entry exists in the database.
Variable Type Required Description
reference string No The reference to check.
ref_id int No The reference id to check.
user_id int No The user id to check.
data string No The data to check for. If you know the data is an array, make sure this value is a serialized array.
type string No The point type to check.
}

Back To Top

About myCred

myCred is a free, open-source and developer friendly points management tool for WordPress powered websites.

Download Rate Plugin

Documentation

  • Add-ons
  • Core Shortcodes
  • F.A.Q.
  • Tutorials
  • Third Party Plugins
  • Code Snippets

Support

  • Product Licenses
  • Customization
  • Support Forums
  • Plugin Changelog
  • Contact

Copyright 2013 - 2019 byWPExperts; All rights reserved. myCred is licensed under GPL 2.0

Terms & Conditions • Use of Cookies • Store Policy • Community Rules

Suggest Codex Example

You can submit suggestions for codex examples that you have available as a public gist. If you are a member on the mycred.me website, you can earn Tokens for each submission. To claim these Tokens, make sure you provide your mycred.me username.

Please make sure the example you submit is relevant and if you include documentation, it's provided in English.

logo
  • Chapters
    • Chapter I – Introduction
    • Chapter II – Getting Started
    • Chapter III – Add-ons
    • Chapter IV – Premium Add-ons
    • Chapter V – For Developers
    • Chapter VI – Reference Guides
  • Categories
    • Actions
    • Classes
    • Constants
    • Filters
    • Functions
    • Objects
    • Shortcodes
    • Hooks
    • Template Tags
  • Packages
    • mycred/api
    • mycred/badge
    • mycred/balance
    • mycred/banking
    • mycred/content
    • mycred/core
    • mycred/coupon
    • mycred/email
    • mycred/game
    • mycred/log
    • mycred/notice
    • mycred/payment
    • mycred/purchase
    • mycred/rank
    • mycred/transfer
  • Store
  • Download