Customize Transfers in 1.5

Description

In this tutorial we will customize the new transfer form in 1.5 allowing your users to add a message to the transfer recipient. If you are using myCred 1.3.x or 1.4.x, you should consult this tutorial instead. Remember that the code examples given in this tutorial goes into your theme’s functions.php file or into an appropriate file of your custom plugin.

For the complete code please consult the “The Final Code” tab above.

The transfer form was re-written in 1.5 by adding in a form element. This means that any HTML form elements inserted in the form will be submitted to the ajax script that handles the transfer action.

What it means is that we no longer need to adjust the form script as we did in previous tutorials!

The action and filter hooks used by the transfer form in previous versions are still available, so that has not changed. Only how the information inside the transfer form is sent has.

Example 1: Transfer Messages

Let your users send a short message to the transfer recipient which is then inserted into the log entry that the recipient sees in their log.

This example requires myCred 1.5.1 or higher. If you are using myCred 1.5, please download a fresh copy of 1.5 from wordpress.org and replace your current version via FTP for this to work.

New in 1.5

Add the Message field

First, we need to add in a new field where users will enter their message. The transfer form offers several ways to do this, but we will in this tutorial use the same action hook as in the previous tutorial and insert it under the recipient field.

/**
 * Step 1 : Insert Message Field
 * @version 1.0
 */
add_action( 'mycred_transfer_form_to', 'mycred_pro_transfer_message_field' );
function mycred_pro_transfer_message_field() {
   echo '<label>Message</label><input type="text" name="transfer-message" id="mycred-transfer-message" value="" placeholder="Optional message to recipient" />';
}

Save the Message

Next up, we will be saving the message using the new mycred_transfer_data filter which allows us to add custom details to each transfer data that is saved into the log.

/**
 * Step 2 : Save Message
 * @version 1.0
 */
add_filter( 'mycred_transfer_data', 'mycred_pro_save_transfer_message', 10, 3 );
function mycred_pro_save_transfer_message( $data, $transaction_id, $post ) {

	// Default message.
	$message = 'No message';

	// If a message is set
	if ( isset( $post['transfer-message'] ) )
		$message = sanitize_text_field( $post['transfer-message'] );

	// Add to the data array
	$data['message'] = $message;

	// return the results
	return $data;

}

Display the Message

Finally we will need to hook in and replace our custom %message% template tag with the message that got saved.

/**
 * Step 3 : Show the message
 * @version 1.0
 */
add_filter( 'mycred_parse_log_entry_transfer', 'mycred_pro_show_message_in_log', 10, 2 );
function mycred_pro_show_message_in_log( $content, $log_entry ) {

	// Unserialize data
	$data = maybe_unserialize( $log_entry->data );

	// Default message
	$message = 'No message';

	if ( isset( $data['message'] ) )
		$message = $data['message'];

	// Replace and return
	return str_replace( '%message%', $message, $content );

}

Example 2: Verify with password

In this example, we will add a password verification to transfers meaning that a user must enter their account password in order for the transfer to be approved. Entering the wrong password or no password will decline the transfer and prompt an error message.

Add the password field

Just as in the previous example, we first need to insert a new input element where the user will be entering their password.

/**
 * Step 1 : Insert Message Field
 * @version 1.0
 */
add_action( 'mycred_transfer_form_to', 'mycred_pro_transfer_message_field' );
function mycred_pro_transfer_message_field() {
 ?>
<input type="text" style="display:none;" value="" />
<label>Confirm with your password</label>
<input type="password" name="pwd" id="mycred-user-pwd" autocomplete="off" value="" placeholder="required" />
<?php
}

You will notice that i have added in an extra input field but I am hiding it via the style attribute. This is to disable the auto-fill functionality in Chrome, which will auto-fill the password field and the first input field before it even if you use autocomplete="off".

Verify Password

Next we will need to hook in to the transfer process just before it is executed and verify the password the user provided. This is done via the wp_check_password function which WordPress provides us. It will hash the provided password and compare it with the one stored in your database.

If the password is missing or incorrect, we kill the process.

/**
 * Step 2 : Verify Password
 * @version 1.0.1
 */
add_action( 'mycred_transfer_ready', 'mycred_pro_verify_transfer_pwd', 1, 4 );
function mycred_pro_verify_transfer_pwd( $post, $prefs, $transfer_addon, $type ) {

	// If the password is empty
	if ( $post['pwd'] == '' )
		die( json_encode( 'Please enter your password!' ) );

	// Get the senders user object
	$sender = wp_get_current_user();

	// Let WordPress check if the provided password is correct
	if ( ! wp_check_password( $post['pwd'], $sender->user_pass, $sender->ID ) )
		die( json_encode( 'Incorrect Password' ) );

}

The messages that we use in the above code snippet will be shown as the button label in your transfer form and if you have set to reload the page after transfer the page will also reload.

BuddyPress: Sort members by current balance

Note that this has not been tested with the latest version of BuddyPress

Description

In this tutorial I will show you how you can sort your BuddyPress members list according to your users current points balances.

All code snippets in this tutorial goes into your themes functions.php file.

Requirements

  • BuddyPress 1.5+
  • myCred Installed and running

The setup

In order for us to sort users according to their balance, we will need to do two things:

  1. Insert the sorting order options into the drop-down menu on our members page.
  2. Adjust the BuddyPress user query to reflect our selected sorting option.

Adjusting the sorting drop-down menu

In the default BuddyPress theme, the drop-down menu that handles sorting on your members page is located in members/index.php and can be extended via the bp_members_directory_order_options action. So the first thing we are going to do is to hook into this action and insert our custom sorting options:

/**
 * Add Sort Members Option
 * @since 0.1
 * @version 1.0
 */
add_action( 'bp_members_directory_order_options', 'mycred_pro_add_sorting_options' );
function mycred_pro_add_sorting_options() { ?>
<option value="points-asc">Points Balance (Ascending)</option>
<option value="points-desc">Points Balance (Descending)</option>
<?php
}

The above example will insert two new options allowing us to sort users according to their current balance either in an Ascending order (0,1,2,3,4) or Descending order (10,9,8,7).

Adjust the BuddyPress User Query

Now that we have our custom options, we need to hook into BuddyPress and adjust the user query to reflect our selected options. To do this, we will use the bp_pre_user_query action which allows us to adjust the database query just before it is executed.

Incorrect SQL queries here will result in either an error message (if WP_DEBUG is enabled) or will return “No users found”.

/**
 * Adjust BP User Query
 * @since 0.1
 * @version 1.0
 */
add_action( 'bp_pre_user_query', 'mycred_pro_pre_user_query' );
function mycred_pro_pre_user_query( $BP_User_Query ) {
	// Only run this if one of our custom options is selected
	if ( in_array( $BP_User_Query->query_vars['type'], array( 'points-asc', 'points-desc' ) ) ) {
		global $wpdb;

		// Adjust SELECT
		$BP_User_Query->uid_clauses['select'] = "
SELECT DISTINCT u.{$BP_User_Query->uid_name} as id 
FROM {$wpdb->users} u 
INNER JOIN {$wpdb->usermeta} um 
	ON ( u.{$BP_User_Query->uid_name} = um.user_id )";

		// Adjust WHERE
		$BP_User_Query->uid_clauses['where'] = "WHERE um.meta_key = 'mycred_default'";

		// Adjust ORDER BY
		$BP_User_Query->uid_clauses['orderby'] = "ORDER BY um.meta_value+0";

		// Adjust ORDER
		$BP_User_Query->uid_clauses['order'] = ( $BP_User_Query->query_vars['type'] == 'points-asc' ) ? 'ASC' : 'DESC';
	}
}

For more information on how BuddyPress handles user searches, you can always check the bp-core-classes.php file which is located in plugins/buddypress/.

Done

That’s it! Save the above codes into your themes functions.php file and upload. If you have any questions or issues, feel free to post them below in the comments section.

BuddyPress User Field: Number of log entries to show

Description

In this short tutorial I will show you how you can setup a custom user field where your members can set how many rows myCRED should show when they are viewing their points history. If the user does not change this value, the default number of rows will be returned.

Requirements

  • myCRED 1.3 +
  • BuddyPress Add-on enabled
  • BuddyPress User Field Component enabled

The User Field

First, we need to create a custom user field which will hold the number of rows a user want to show. As with all user fields, we create them under the “Users” menu item in our admin area.

It does not matter under which group you save this field or what you call it. Just make sure you select “Text Field” as field type and make a note of the title you set.

Hooking into myCRED

The number of rows shown for each users points history is set by the mycred_bp_history_num_to_show filter. We can use this filter to grab our users set value and if it’s not empty, use that value.

add_filter( 'mycred_bp_history_num_to_show', 'buddypress_number_of_rows_to_show' );
function buddypress_number_of_rows_to_show( $num ) {
	$user_id = bp_displayed_user_id();
	$number = xprofile_get_field_data( 'Your User Fields Title', $user_id );
	if ( ! empty( $number ) )
		return $number;

	return $num;
}

Make sure you replace the above field name with your own title and make sure it matches exactly.

Done!

Add the above code to your themes functions.php file and upload. Once done, visit your BuddyPress profile and edit your settings. Set the number of rows you want to see and save. If you visit the myCRED Log page in your BuddyPress profile, you should now see the set number of rows (if there are that many).

A simple referral program awarding points

Warning! This tutorial will not work with myCred 1.4 or higher. If you are using version 1.4 or higher you should instead use the “Points for referrals” hook. This tutorial is for those using myCred 1.3 or lower.

Description

In this tutorial I will show you a very basic referral system where users are awarded points for visitors who use their referral link to visit your website. To avoid multiple entries, we will log the visitors IP address each time points are awarded.

All code snippets are placed in your themes functions.php file.

Requirements

  • myCred 1.2 or higher

A Referral ID

First we need to establish what we would use as a identifier for each user. The simplest solution would be to use their ID, which we know will always be unique or generate a custom token for each user.

So we start of by creating a custom function which will return the current users referral ID:

// Using the Users ID as referral ID
function mycred_get_my_ref_id()
{
	if ( !is_user_logged_in() ) return;
	return get_current_user_id();
}

// Generating a custom token for each user and save it to prevent
// new tokens from being generated each time this function runs
function mycred_get_my_ref_id()
{
	if ( !is_user_logged_in() ) return;

	$user_id = get_current_user_id();
	$ref = get_user_meta( $user_id, 'ref_id', true );
	if ( empty( $ref ) ) {
		$ref = wp_generate_password( 6 );
		update_user_meta( $user_id, 'ref_id', $ref );
	}
	return urlencode( $ref );
}

In the second example we use the wp_generate_password() function to generate a unique 6 character long token. This token is then saved as a user meta under the “ref_id” id.

Show Users Their ID

Next we will need to insert this function somewhere on our website where users can see it. For this tutorial, we will show it to users when they edit their profile in the admin area.

add_action( 'profile_personal_options', 'show_users_referral_id' );
function show_users_referral_id( $user )
{
	$ref_id = mycred_get_my_ref_id(); ?>

<p>Refer users to our website and earn points!</p>
<p>Your referral ID is: <?php echo $ref_id; ?></p>
<?php
}

Alternatively, we can create a custom function to automatically add this referral ID to your blogs home url:

function mycred_get_ref_for_home()
{
	if ( !is_user_logged_in() ) return;
	return add_query_arg( array( 'ref' => mycred_get_my_ref_id() ), home_url() );
}

We can then use this function to show the current user their referral ID attached to your websites home url. Using the above user profile example:

add_action( 'profile_personal_options', 'show_users_referral_id' );
function show_users_referral_id( $user )
{ ?>

<p>Refer users to our website and earn points!</p>
<p><?php echo mycred_get_ref_for_home(); ?></p>
<?php
}

The above code will output:

Refer users to our website and earn points!

front page

While our custom mycred_get_ref_for_home() function will attach the referral ID to our home url, we can create a new function to attach it to a pre-defined URL. You could then use this function anywhere in your theme to show your users the referral ID for any given page/post.

function mycred_get_ref_for_url( $url = '' )
{
	if ( !is_user_logged_in() || empty( $url ) ) return;
	return add_query_arg( array( 'ref' => mycred_get_my_ref_id() ), $url );
}

You could use this function for example for your store products, allowing your users to refer users to specific products and still being able to receive points for the referral.

Detecting Referrals

Now we just need to detect visitors who are arriving though one of these referrals. For this we will need two custom functions. First a function that hooks in to WordPress to do the actual detection and a function that will find which user the referral ID belongs to. This of course is not necessary if you are using your users ID as the referral ID.

Lets start with detecting. We will hook in to WordPress pretty early and check if the “ref” argument is set in the visitors URL. If it is, we will try and find which user it belongs to, make sure our users is not using their own referral IDs to try and get points, check the visitors IP address to make sure we do not award points multiple times and finally remove the ref argument to prevent multiple database queries.

add_action( 'template_redirect', 'mycred_catch_referred_users' );
function mycred_catch_referred_users()
{
	if ( !isset( $_GET['ref'] ) ) return;

	if ( !empty( $_GET['ref'] ) ) {
		$ref_id = urldecode( $_REQUEST['ref'] );
		$user_id = mycred_get_userid_from_ref( $ref_id );
		if ( $user_id === false ) return;
		if ( is_user_logged_in() && get_current_user_id() == $user_id ) return;

		$mycred = mycred_get_settings();
		$IP = $_SERVER['REMOTE_ADDR'];
		if ( empty( $IP ) ) return;
		if ( ! $mycred->has_entry( 'visitor_referring', '', $user_id, $IP ) ) {
			$mycred->add_creds(
				'visitor_referring',
				$user_id,
				1,
				'%plural% for visitor referral',
				'',
				$IP
			);
		}

		wp_redirect( remove_query_arg( 'ref' ) );
		exit;
	}
}

Next we will need to create the mycred_get_userid_from_ref() function which will do the actual database query:

function mycred_get_userid_from_ref( $ref_id = NULL )
{
	if ( $ref_id === NULL ) return false;

	global $wpdb;
	$user_id = $wpdb->get_var( $wpdb->prepare( "SELECT user_id FROM {$wpdb->usermeta} WHERE meta_key = %s AND meta_value = %s;", 'ref_id', $ref_id ) );
	$wpdb->flush();
	if ( $user_id === NULL ) return false;

	return intval( $user_id );
}

Now all together

All the functions together:

/**
 * Get Current Users Ref ID
 * Returns the current users ref ID.
 * @version 1.0
 */
function mycred_get_my_ref_id()
{
	if ( !is_user_logged_in() ) return;

	$user_id = get_current_user_id();
	$ref = get_user_meta( $user_id, 'ref_id', true );
	if ( empty( $ref ) ) {
		$ref = wp_generate_password( 6 );
		update_user_meta( $user_id, 'ref_id', $ref );
	}
	return urlencode( $ref );
}

/**
 * Add Ref ID to Home URL
 * Appends the current users refid to the sites home url.
 * @version 1.0
 */
function mycred_get_ref_for_home()
{
	if ( !is_user_logged_in() ) return;
	return add_query_arg( array( 'ref' => mycred_get_my_ref_id() ), home_url() );
}

/**
 * Add Ref ID to URL
 * Appends the current users refid to a given url.
 * @version 1.0
 */
function mycred_get_ref_for_url( $url = '' )
{
	if ( !is_user_logged_in() || empty( $url ) ) return;
	return add_query_arg( array( 'ref' => mycred_get_my_ref_id() ), $url );
}

/**
 * Insert Users Ref ID
 * Inserts the current users referral ID in the profile edit page.
 * @version 1.0
 */
add_action( 'profile_personal_options', 'show_users_referral_id' );
function show_users_referral_id( $user )
{ ?>

<p>Refer users to our website and earn points!</p>
<p><?php echo mycred_get_ref_for_home(); ?></p>
<?php
}

/**
 * Get User ID from Ref ID
 * Returns the user id of a given referral id.
 * @version 1.0
 */
function mycred_get_userid_from_ref( $ref_id = NULL )
{
	if ( $ref_id === NULL ) return false;

	global $wpdb;
	$user_id = $wpdb->get_var( $wpdb->prepare( "SELECT user_id FROM {$wpdb->usermeta} WHERE meta_key = %s AND meta_value = %s;", 'ref_id', $ref_id ) );
	$wpdb->flush();
	if ( $user_id === NULL ) return false;

	return intval( $user_id );
}

/**
 * Detect Referrer
 * Checks if user has been referred, awards points if it is
 * a unique IP and removed the ref query argument.
 * @version 1.0
 */
add_action( 'template_redirect', 'mycred_catch_referred_users' );
function mycred_catch_referred_users()
{
	if ( !isset( $_GET['ref'] ) ) return;

	if ( !empty( $_GET['ref'] ) ) {
		$ref_id = urldecode( $_GET['ref'] );
		$user_id = mycred_get_userid_from_ref( $ref_id );
		if ( $user_id !== false ) return;
		if ( is_user_logged_in() && get_current_user_id() == $user_id ) return;

		$mycred = mycred_get_settings();
		$IP = $_SERVER['REMOTE_ADDR'];
		if ( empty( $IP ) ) return;
		if ( ! $mycred->has_entry( 'visitor_referring', '', $user_id, $IP ) ) {
			$mycred->add_creds(
				'visitor_referring',
				$user_id,
				1,
				'%plural% for visitor referral',
				'',
				$IP
			);
		}
		wp_redirect( remove_query_arg( 'ref' ) );
		exit;
	}
}

Note If you are using this code in your localhost server, your IP might be an empty string, in which case you will be awarded points each time you use the referral id!

Done

Thats it. As promised this is a very simple referral system that awards 1 point for each unique visitor that visits our website using a referral link. If you have any questions please feel free to comment below.

Update

Several users has requested information on how to modify this tutorial and add points when users signup using this referral system. To accomplish this, we need to do two things. First we will need to adjust the detection script to set a cookie for the current user and hook into WordPress registrations where we check for this cookie and award points for successful signups.

Lets start with the detection script.

/**
 * Detect Referrer
 * Checks if user has been referred, awards points if it is
 * a unique IP and removed the ref query argument.
 * @version 1.0
 */
add_action( 'template_redirect', 'mycred_catch_referred_users' );
function mycred_catch_referred_users()
{
	if ( !isset( $_GET['ref'] ) ) return;

	if ( !empty( $_GET['ref'] ) ) {
		$ref_id = urldecode( $_GET['ref'] );
		$user_id = mycred_get_userid_from_ref( $ref_id );
		if ( $user_id === false ) return;
		if ( is_user_logged_in() && get_current_user_id() == $user_id ) return;

		$mycred = mycred_get_settings();
		$IP = $_SERVER['REMOTE_ADDR'];
		if ( empty( $IP ) ) return;
		if ( !$mycred->has_entry( 'visitor_referring', '', $user_id, $IP ) ) {
			$mycred->add_creds(
				'visitor_referring',
				$user_id,
				1,
				'%plural% for visitor referral',
				'',
				$IP
			);
		}
		// Set a cookie in case user signs up
		setcookie( 'signup_ref', $ref_id, time()+3600*24 );
		wp_redirect( remove_query_arg( 'ref' ) );
		exit;
	}
}

We give the user a new cookie called “signup_ref” which will be valid for one day. For more information on how setcookie work, please consult the PHP documentation.

Next we hook into user_register which fires when a new user has signed up on our website:

add_action( 'user_register', 'check_for_referral_at_signup' );
function check_for_referral_at_signup( $user_id )
{
	// Check for cookie
	if ( isset( $_COOKIE['signup_ref'] ) ) {
		// Get the referrers ID
		$ref_user_id = mycred_get_userid_from_ref( $_COOKIE['signup_ref'] );

		// Make sure ref_id is valid, if not delete the cookie to avoid further checks
		if ( $ref_user_id === false ) {
			setcookie( 'signup_ref', $_COOKIE['signup_ref'], time()-3600 );
			return;
		}

		// Load myCred
		$mycred = mycred_get_settings();

		// Make sure this is unique
		if ( !$mycred->has_entry( 'signup_referral', $user_id, $ref_user_id ) ) {
			$mycred->add_creds(
				'signup_referral',
				$ref_user_id,
				1,
				'%plural% for signup referral',
				$user_id,
				array( 'ref_type' => 'user' )
			);
		}

		// Remove Cookie by setting the expiration date in the past
		setcookie( 'signup_ref', $ref_id, time()-3600 );
	}
}

As you can see it is pretty straight forward. You would need to add your own log entry template and points amount and as you can see, I have added support for User related template tags in case you want to show the new users name etc.

Important There is one important thing to remember! The above example relies on the user_register action to fire. In case you use a plugin which customizes or adjusts your signup process, you will need to make sure that this plugin fires this action. If it does not, then no points will be awarded! In these cases you would need to check if your plugin offers some other action or filter you could use instead.

Awarding points for users who “Share” a post.

You can award points for real shares to social media sites in myCred 1.5 using the ShareThis plugin.

Description

In this tutorial I will show you how to use the mycred_link shortcode to award users points for “sharing” a post on your website on Facebook, Google+, Twitter or Pinterest.

Important!

Using the mycred_link shortcode will award or deduct users points for that click, however it does not guaranty that the user actually “shares” the content. It is essentially just “Points for clicking on links”.

Note
Code snippets presented here goes in your custom plugin or in your themes functions.php file.

Requirements

  • myCred 1.1
  • The “Points for clicking on links” Hook enabled

The plan

For this tutorial, we will create a new shortcode that will work just as the mycred_link shortcode, with one difference. Instead of entering a URL for the href attribute, we will only enter the social media sites name. The shortcode then append the appropriate API url with the current pages address.

This tutorial will not require us to make any changes to myCred or the mycred_link shortcode!

The Shortcode

Lets start constructing our new shortcode. For this tutorial I have named it “mycred_share_this”.

add_shortcode( 'mycred_share_this', 'mycred_render_shortcode_share_this' );
function mycred_render_shortcode_share_this( $attr, $link_title )
{

}

Since our shortcode will do exactly the same thing as the mycred_link shortcode, we can just pass on our variables directly to the function that renders it.

add_shortcode( 'mycred_share_this', 'mycred_render_shortcode_share_this' );
function mycred_render_shortcode_share_this( $attr, $link_title )
{
	return mycred_render_shortcode_link( $attr, $link_title );
}

Facebook Example

At this stage, we have two shortcodes doing the exact same thing, so now we will need to make the url adjustment. Instead of a URL we will simply pass on the social media site names i.e. [mycred_share_this href=”facebook”].

Facebook offers an easy share dialog that only requires a urlencoded address.

add_shortcode( 'mycred_share_this', 'mycred_render_shortcode_share_this' );
function mycred_render_shortcode_share_this( $attr, $link_title )
{
	$url = get_permalink();

	if ( $attr['href'] == 'facebook' )
		$attr['href'] = 'https://www.facebook.com/sharer/sharer.php?u=' . urlencode( $url );

	return mycred_render_shortcode_link( $attr, $link_title );
}

As you can see it is pretty straight forward. We get the current pages url though get_permalink() and append it to the share dialog url. Below I have entered a few different social media sites but you can add others you might find.

add_shortcode( 'mycred_share_this', 'mycred_render_shortcode_share_this' );
function mycred_render_shortcode_share_this( $attr, $link_title )
{
	$url = get_permalink();

	if ( $attr['href'] == 'facebook' )
		$attr['href'] = 'https://www.facebook.com/sharer/sharer.php?u=' . urlencode( $url );
	elseif ( $attr['href'] == 'twitter' )
		$attr['href'] = 'http://twitter.com/home?status=' . urlencode( $url );
	elseif ( $attr['href'] == 'google' )
		$attr['href'] = 'http://plus.google.com/share?url=' . urlencode( $url );
	elseif ( $attr['href'] == 'pinterest' )
		$attr['href'] = 'http://pinterest.com/pin/create/button/?url=' . urlencode( $url );

	return mycred_render_shortcode_link( $attr, $link_title );
}

If you want to limit so users only get points once for each “share”, you can set the “Points for clicking on links” to limit once for each URL.

Remember that you would need to add target=”_blank” for these type of links or just enforce it automatically:

add_shortcode( 'mycred_share_this', 'mycred_render_shortcode_share_this' );
function mycred_render_shortcode_share_this( $attr, $link_title )
{
	// Get URL (we assume you only use this shortcode inside the loop)
	$url = get_permalink();

	// Append social media share urls
	if ( $attr['href'] == 'facebook' )
		$attr['href'] = 'https://www.facebook.com/sharer/sharer.php?u=' . urlencode( $url );
	elseif ( $attr['href'] == 'twitter' )
		$attr['href'] = 'http://twitter.com/home?status=' . urlencode( $url );
	elseif ( $attr['href'] == 'google' )
		$attr['href'] = 'http://plus.google.com/share?url=' . urlencode( $url );
	elseif ( $attr['href'] == 'pinterest' )
		$attr['href'] = 'http://pinterest.com/pin/create/button/?url=' . urlencode( $url );

	// Always make links open in a new window
	$attr['target'] = '_blank';

	// Pass it on
	return mycred_render_shortcode_link( $attr, $link_title );
}

 

Add Referral ID to the URL

You can combine this custom code and add in the users referral ID allowing them to earn points for users who use the shared link. Of course it requires you to have the “Points for referrals” hook enabled:

add_shortcode( 'mycred_share_this', 'mycred_render_shortcode_share_this' );
function mycred_render_shortcode_share_this( $attr, $link_title )
{
	// Get URL (we assume you only use this shortcode inside the loop)
	$url = get_permalink();

	// Add affiliate link (requires myCRED 1.5.3 or higher)
	$url = mycred_render_affiliate_link( array( 'url' => $url ) );
	// Append social media share urls
	if ( $attr['href'] == 'facebook' )
		$attr['href'] = 'https://www.facebook.com/sharer/sharer.php?u=' . urlencode( $url );
	elseif ( $attr['href'] == 'twitter' )
		$attr['href'] = 'http://twitter.com/home?status=' . urlencode( $url );
	elseif ( $attr['href'] == 'google' )
		$attr['href'] = 'http://plus.google.com/share?url=' . urlencode( $url );
	elseif ( $attr['href'] == 'pinterest' )
		$attr['href'] = 'http://pinterest.com/pin/create/button/?url=' . urlencode( $url );

	// Always make links open in a new window
	$attr['target'] = '_blank';

	// Pass it on
	return mycred_render_shortcode_link( $attr, $link_title );
}

 

Done

And there you go, now we have a custom shortcode that you can use to let your users gain points for “sharing” your posts or pages. If you have any further questions, feel free to post them below.

Download

Adjust comment layout according to rank

Description

In this tutorial we will customize our websites comment layout according to the comment authors rank. I will be using the WordPress TwentyTwelve Theme but most of these examples should work on most WordPress themes.

Requirements

  • myCred 1.1 or higher.
  • Basic understanding of WordPress Themes.

Add Custom Comment Class

First off we will add a comment authors rank (if they are members) to the comment class which will allow us to add custom CSS styling to “highlight” different ranks.

To do this, we will start by creating a custom filter for the comment_class filter hook and place this filter in our theme’s functions.php file.

add_filter( 'comment_class', 'insert_rank_into_comment_class', 10, 4 );
function insert_rank_into_comment_class( $classes, $class, $comment_id, $post_id )
{
	return $classes;
}

The first thing we need to do is to make sure that the comment author is a registered member so we can get the users ID.

Next, we will add the rank name as a class rank-{rank_name}. To get a users rank, we will be using the mycred_get_users_rank function.

add_filter( 'comment_class', 'insert_rank_into_comment_class', 10, 4 );
function insert_rank_into_comment_class( $classes, $class, $comment_id, $post_id )
{
	$comment = get_comment( $comment_id );
	if ( $comment->user_id == 0 ) return $classes;

	$classes[] = 'rank-' . mycred_get_users_rank( $comment->user_id, 'post_name' );

	return $classes;
}

Now, each comment will have a custom class formated as rank-{rank_name} allowing us to add CSS Styling:

// Styling for comments made by members with "junior" rank
.commentlist .rank-junior { }
// Styling for comments made by members with "veteran" rank
.commentlist .rank-veteran { }

Example: Change the Comment Authors Name to red color if they have the “veteran” rank:

.commentlist .rank-veteran cite {
	color: red;
}

ranks-commenthigh

With some clever CSS styling you could do almost any type of adjustments.

Adding Rank Details

Styling comments only gets us so far. What if we want to include the comment authors rank and rank logo?

To do this, we will need to adjust the comment template. In the TwentyTwelve theme, this is done though the twentytwelve_comment() function which is located in the functions.php file and looks like this:

function twentytwelve_comment( $comment, $args, $depth ) {
	$GLOBALS['comment'] = $comment;
	switch ( $comment->comment_type ) :
		case 'pingback' :
		case 'trackback' :
		// Display trackbacks differently than normal comments.
	?>
	<li <?php comment_class(); ?> id="comment-<?php comment_ID(); ?>">
		<p><?php _e( 'Pingback:', 'twentytwelve' ); ?> <?php comment_author_link(); ?> <?php edit_comment_link( __( '(Edit)', 'twentytwelve' ), '<span class="edit-link">', '</span>' ); ?></p>
	<?php
			break;
		default :
		// Proceed with normal comments.
		global $post;
	?>
	<li <?php comment_class(); ?> id="li-comment-<?php comment_ID(); ?>">
		<article id="comment-<?php comment_ID(); ?>" class="comment">
			<header class="comment-meta comment-author vcard">
				<?php
					echo get_avatar( $comment, 44 );
					printf( '<cite class="fn">%1$s %2$s</cite>',
						get_comment_author_link(),
						// If current post author is also comment author, make it known visually.
						( $comment->user_id === $post->post_author ) ? '<span> ' . __( 'Post author', 'twentytwelve' ) . '</span>' : ''
					);
					printf( '<a href="%1$s"><time datetime="%2$s">%3$s</time></a>',
						esc_url( get_comment_link( $comment->comment_ID ) ),
						get_comment_time( 'c' ),
						/* translators: 1: date, 2: time */
						sprintf( __( '%1$s at %2$s', 'twentytwelve' ), get_comment_date(), get_comment_time() )
					);
				?>
			</header><!-- .comment-meta -->

			<?php if ( '0' == $comment->comment_approved ) : ?>
				<p class="comment-awaiting-moderation"><?php _e( 'Your comment is awaiting moderation.', 'twentytwelve' ); ?></p>
			<?php endif; ?>

			<section class="comment-content comment">
				<?php comment_text(); ?>
				<?php edit_comment_link( __( 'Edit', 'twentytwelve' ), '<p class="edit-link">', '</p>' ); ?>
			</section><!-- .comment-content -->

			<div class="reply">
				<?php comment_reply_link( array_merge( $args, array( 'reply_text' => __( 'Reply', 'twentytwelve' ), 'after' => ' ↓', 'depth' => $depth, 'max_depth' => $args['max_depth'] ) ) ); ?>
			</div><!-- .reply -->
		</article><!-- #comment-## -->
	<?php
		break;
	endswitch; // end comment_type check
}

Using the mycred_get_users_rank function we first insert the rank logo directly after the avatar, then after the timestamp we add a new row where we show the users rank:

function twentytwelve_comment( $comment, $args, $depth ) {
	$GLOBALS['comment'] = $comment;
	switch ( $comment->comment_type ) :
		case 'pingback' :
		case 'trackback' :
		// Display trackbacks differently than normal comments.
	?>
	<li <?php comment_class(); ?> id="comment-<?php comment_ID(); ?>">
		<p><?php _e( 'Pingback:', 'twentytwelve' ); ?> <?php comment_author_link(); ?> <?php edit_comment_link( __( '(Edit)', 'twentytwelve' ), '<span class="edit-link">', '</span>' ); ?></p>
	<?php
			break;
		default :
		// Proceed with normal comments.
		global $post;
	?>
	<li <?php comment_class(); ?> id="li-comment-<?php comment_ID(); ?>">
		<article id="comment-<?php comment_ID(); ?>" class="comment">
			<header class="comment-meta comment-author vcard">
				<?php
					echo get_avatar( $comment, 44 );
					// Insert rank logo
					if ( $comment->user_id != 0 )
						echo mycred_get_users_rank( $comment->user_id, 'logo', 'post-thumbnail', array( 'class' => 'mycred-rank' ) );

					printf( '<cite class="fn">%1$s %2$s</cite>',
						get_comment_author_link(),
						// If current post author is also comment author, make it known visually.
						( $comment->user_id === $post->post_author ) ? '<span> ' . __( 'Post author', 'twentytwelve' ) . '</span>' : ''
					);
					printf( '<a href="%1$s"><time datetime="%2$s">%3$s</time></a>',
						esc_url( get_comment_link( $comment->comment_ID ) ),
						get_comment_time( 'c' ),
						/* translators: 1: date, 2: time */
						sprintf( __( '%1$s at %2$s', 'twentytwelve' ), get_comment_date(), get_comment_time() )
					);
					// Insert rank title
					if ( $comment->user_id != 0 )
						echo '<div class="fn authors-rank" style="margin-left:6.071428571rem;">Rank: ' . mycred_get_users_rank( $comment->user_id ) . '</div>';
				?>
			</header><!-- .comment-meta -->

			<?php if ( '0' == $comment->comment_approved ) : ?>
				<p class="comment-awaiting-moderation"><?php _e( 'Your comment is awaiting moderation.', 'twentytwelve' ); ?></p>
			<?php endif; ?>

			<section class="comment-content comment">
				<?php comment_text(); ?>
				<?php edit_comment_link( __( 'Edit', 'twentytwelve' ), '<p class="edit-link">', '</p>' ); ?>
			</section><!-- .comment-content -->

			<div class="reply">
				<?php comment_reply_link( array_merge( $args, array( 'reply_text' => __( 'Reply', 'twentytwelve' ), 'after' => ' ↓', 'depth' => $depth, 'max_depth' => $args['max_depth'] ) ) ); ?>
			</div><!-- .reply -->
		</article><!-- #comment-## -->
	<?php
		break;
	endswitch; // end comment_type check
}

How-to-guide-rankscomplus

You can of course add these details anywhere you want in your comment template, this is just one example.

Done

If you have any questions on how to further customize comments based on users rank, feel free to post them below.

Comment appreciation with points

Description

In this tutorial we will add the myCred_send shortcode to your posts comments to allow users to give points to the comment author as a form of “Appreciation”.

Requirements

  • This tutorial requires myCred version 1.1 or higher.

Hooking into Comments

For this tutorial, we will be hooking into the comment text using the comment_text filter and append the myCred_send shortcode to the end of the text which will generate a simple button that users can click on to send 1 point to the comment author.

First, lets construct our custom filter:

add_filter( 'comment_text', 'my_custom_comment_text', 10, 2 );
function my_custom_comment_text( $comment_text, $comment )
{
	return $comment_text;
}

The WordPress codex tells us that the comment_text filter has two variables. The comment text itself and the comment object. Since we need to get the comment authors ID, we will need to call both of these variables.

The first thing our filter needs to do is to make sure that the current user is logged in, that the comment author is a registered member and that this is not the admin area. If this is not the case, we will return the text without the shortcode:

function my_custom_comment_text( $comment_text, $comment )
{
	// Make sure the current user is logged in
	if ( !is_user_logged_in() || $comment->user_id == 0 || is_admin() )
		return $comment_text;

	return $comment_text;
}

Note that if we do not include the is_admin() check, the appreciation button will be visible in the comment editor screen as well!

Next up we will load the myCred Settings Object and the current users ID. Once we have these we will need to make sure that neither the current user or the comment authors are “excluded” and that these two are not the same:

function my_custom_comment_text( $comment_text, $comment )
{
	// Make sure the current user is logged in
	if ( !is_user_logged_in() || $comment->user_id == 0 || is_admin() )
		return $comment_text;

	// Prep
	$mycred = mycred();
	$cui = get_current_user_id();

	// Make sure the current user is not the comment author
	if ( $cui == $comment->user_id ) return $comment_text;

	// Make sure the current user is not excluded
	if ( $mycred->exclude_user( $cui ) ) return $comment_text;

	// Make sure the comment author is not excluded
	if ( $mycred->exclude_user( $comment->user_id ) ) return $comment_text;

	return $comment_text;
}

Finally we will include the mycred_shortcode. Feel free to change the shortcode variables to something that suits you. In the below example, users will be able to send 1 point to the comment author and we call this action “Comment Appreciation”:

add_filter( 'comment_text', 'my_custom_comment_text', 10, 2 );
function my_custom_comment_text( $comment_text, $comment )
{
	// Make sure the current user is logged in
	if ( !is_user_logged_in() || $comment->user_id == 0 || is_admin() )
		return $comment_text;

	// Prep
	$mycred = mycred();
	$cui = get_current_user_id();

	// Make sure the current user is not the comment author
	if ( $cui == $comment->user_id ) return $comment_text;

	// Make sure the current user is not excldued
	if ( $mycred->exclude_user( $cui ) ) return $comment_text;

	// Make sure the comment author is not excluded
	if ( $mycred->exclude_user( $comment->user_id ) ) return $comment_text;

	// Prep shortcode details
	$user_id = $comment->user_id;
	$amount = 1;
	$label = 'Give 1 Point';
	$ref = 'comment_appreciation';
	$entry = 'Comment Appreciation';

	// Append shortcode to the end of the comment text
	$add_points = '[mycred_send to="' . $user_id . '" amount="' . $amount . '" log="' . $entry . '"]' . $label . '[/mycred_send]';
	$comment_text .= '
<div class="comment-like">' . do_shortcode( $add_points ) . '</div>';

	// Return result
	return $comment_text;
}

Done

And that’s it. Place the code in your themes functions.php file and upload! Remember that if you are using an account that is excluded or if you are the comment author you will not be able to do any Comment Appreciation!

Introduction to myCred Ranks

Description

In this tutorial I will introduce you to the myCred Ranks add-on. We will set up a few ranks and I will show you how to present ranks for users and how to customize your theme to accommodate ranks via custom templates.

Requirements

  • myCred 1.1 or higher.
  • Basic understanding of how WordPress theme template files work.

Introduction

The myCred Ranks add-on allows you to setup ranks based on how many points a user has. Ranks are custom post types and are edited and created just as posts or pages.

Each rank holds three sets of information: The Ranks Title, The Points Requirement and optionally the Rank “Logo” which is the Featured Image feature in WordPress.

There is no limit to how many ranks you can have, as long as the points requirements does not overlap.

Just as with posts and pages, you can save Ranks as drafts, Publish a rank or Schedule a rank for being published at a later date.

When a rank is “Published”, myCred will run though all of your users and assign those who meet the points requirements to the rank you just created. So draft ranks or scheduled ranks are not assigned until they get published!

While Ranks also support ranks to be set as “Private” it is not recommended. The rank shortcodes that present ranks on your website will only display Public Published ranks! On the other hand, if you use custom theme template files for your ranks, you could technically display “Private” ranks just as posts for those who can see them.

Note that Rank editing and creation requires you to have the same capabilities as when publishing pages. This means that if you are using the default WordPress roles, only Administrators will have access to editing and creating ranks.

To start using Ranks, simply visit the “Add-ons” sub-menu page under “myCred” in your Admin area and enable the “Ranks” add-on.

ranks-activateaddon

Settings

To change your Ranks settings, visit the “Settings” sub-menu under “myCred” and click on “Ranks” section.

Here you can adjust what features the Rank post type should offer, by default only rank title, point requirement and featured image is enabled but myCred as of 1.1.1 also supports the editor, comments, excerpt or page attributes.

By default, myCred ranks are not public. This means that the only way to see ranks or to list ranks is by using shortcodes. You can however set ranks to be public enabling you to create archives or even custom single layouts in your theme folder. For more information on how to do this, have a look at this tutorial.

You can also select in what order ranks are shown both in the admin area and in front.

ranks-settings

Adding Ranks

ranks-default

By default, myCred will create a rank called “Newbie”. This rank’s points requirement is set to range from 0 to 999999. Before we add a new rank, we start with editing this Newbie rank to suit our needs. Since this will be our lowest, default rank, we will leave the minimum points requirement at zero but we will change the maximum to 99.

Furthermore, in this tutorial, the newbie rank will have no logo, of course you can have one if you want.

Adjusting the default Rank

Once we have changed our maximum point requirement we click “Update” to save our settings. When our changes are saved, we click on “Add New” button next to the “Edit Rank” title.

We will call our new rank “Junior” and this ranks point requirement will run from a minimum of 100 to a maximum of 999.

You can of course rename the default rank to a name or even delete it and just start fresh.

ranks-addnew

Rank Logo

For this rank, we are going to add a logo. Just like any other Featured Image, we can either upload an image to use or select one from your Media Library. When you have found your image, simply select it and click “Set Featured Image”. Once your image is visible in your “Featured Image” metabox, we click “Publish”.

ranks-selectlogo

Rince and repeat

Now that we have created our new rank, we can create as many ranks as we need. Simply repeat the above steps for each rank until you’re satisfied.

Assigning Ranks

There are three instances when myCred assigns a rank:

  • When a rank is published.
  • When users signup and become members on your website.
  • When a user gains or loses points.

This means that myCred will assign roles for your users automatically without the need for you to do it individually. This also means that the only way for you to manually adjust a users rank is to award / deduct points form the user.

Showing Rank

Besides showing ranks though your themes template files, which we will look at in a second, you can also show your users ranks though the myCred Balance widget or through the use of custom shortcodes. But lets start with the widget.

myCred Balance Widget

When editing the balance widget, you get the option to set the “Layout” for how the balance is presented. You could include a users rank here by using the template tag %rank% to show the users rank title or %rank_logo% to show the rank logo.

ranks-widgetsetup

Depending on your theme, you might need to add some custom CSS styling to the image or title suit your website layout.

ranks-widgetresult

Shortcodes

myCred Ranks comes with three different shortcodes that you can place in your page or post content.

    • mycred_my_rank
      Use this shortcode to show a specific users rank or by default, the current logged in users rank. Consult the codex for all available options.
    • mycred_users_of_rank
      Use this shortcode to display users of a specific rank. Consult the codex for all available options.
    • mycred_users_of_all_ranks
      Use this shortcode to show users of each and ever published rank in order. Consult the codex for all available options.

Done

That is the end of this introductory tutorial. If you have any questions feel free to post them below.

Feel free to post your questions or remarks below.

Add Custom Template Tags

Description

myCred offers a growing number of template tags for you to use in your installation, but for some, this is simply not enough. In this tutorial I will show how you can add custom template tags for general, amount related, post related, comment related and user related.

Requirements

  • myCred version 1.1 or higher.
  • Basic understanding of how WordPress filter hooks work.

General Template Tags

General template tags are one of the most used template tags in myCred and is run either individually or when any other type of template tags are parsed.

To add our own template tags we will need to use the myCred_parse_tags_general fiter. In the code snippet below, we will add a new template tag %register_url% which will return a link to your websites default registration page.

add_filter( 'mycred_parse_tags_general', 'my_custom_general_template_tags' );
function my_custom_general_template_tags( $content )
{
	$content = str_replace( '%register_url%', get_bloginfo( 'url' ) . '/wp-login.php?action=register', $content );
	return $content; 
}

This code goes into your themes functions.php file.

Amount Related Template Tags

There are only two amount related template tags, %cred% and %cred_f% which will return a given amount either in plain format or formatted according to your myCred installation.

To add our own template tags we will need to use the mycred_parse_tags_amount fiter. In the code snippet below, we will add a new template tag %dollars% which will return the given amount with a dollar sign added as a prefix.

add_filter( 'mycred_parse_tags_amount', 'my_custom_amount_template_tags', 10, 2 );
function my_custom_amount_template_tags( $content, $amount )
{
	$content = str_replace( '%dollars%', '$ ' . $amount, $content );
	return $content; 
}

This code goes into your themes functions.php file.

Post Related Template Tags

Post related template tags are used when there is a reference to a post id allowing us to grab that posts details and build template tags like %link_with_title% which will return the permalink to the given post.

To add our own template tags we will need to use the mycred_parse_tags_post fiter. In the code snippet below, we will add a new template tag %post_status% which will return the given post’s current status.

add_filter( 'mycred_parse_tags_post', 'my_custom_post_template_tags', 10, 3 );
function my_custom_post_template_tags( $content, $post, $data )
{
	$content = str_replace( '%post_status%', $post->post_status, $content );
	return $content; 
}

This code goes into your themes functions.php file.

Comment Related Template Tags

These template tags are only used in the “Points for Commenting” hook by default and contains template tags for the most commonly required comment details.

To add our own template tags we will need to use the mycred_parse_tags_comment fiter. In the code snippet below, we will add a new template tag %IP% which will return the IP address of the comment author.

add_filter( 'mycred_parse_tags_comment', 'my_custom_comment_template_tags', 10, 3 );
function my_custom_comment_template_tags( $content, $comment, $data )
{
	$content = str_replace( '%IP%', $comment->comment_author_IP, $content );
	return $content; 
}

This code goes into your themes functions.php file.

User Related Template Tags

User related template tags is the second most used template tag types in myCred and allows you to include a vast range of user details.

This filter is also used by for example the Rankings Add-on to add new custom template tags for rank names and logos.

To add our own template tags we will need to use the mycred_parse_tags_user fiter. In the code snippet below, we will add two new template tags %avatar_small% and %avatar_large%, which will return given users avatar either in a smaller version ( 32px by 32px ) or a larger version ( 64px by 64px ).

add_filter( 'mycred_parse_tags_user', 'my_custom_user_template_tags', 10, 3 );
function my_custom_user_template_tags( $content, $user, $data )
{
	$content = str_replace( '%avatar_small%', get_avatar( $user->ID, 32 ), $content );
	$content = str_replace( '%avatar_large%', get_avatar( $user->ID, 64 ), $content );
	return $content; 
}

This code goes into your themes functions.php file.

Final Notes

While you can add support for custom template tags though other filters as well, i.e. the myCred_ranking_row filter, if you want to add a custom template tags that can be used in more than one instance, you should use the above filters.

If you only want to add a shortcode for specific instances i.e. when showing ranking rows in the myCred Balance Widget, you should use that particular filter instead.

Block users with negative balances

Navigation:

  1. Description
  2. Requirements
  3. Authenticate
  4. Done

Description

In this tutorial, I will show you how you can block users from logging in if their account balance goes into minus.

For this tutorial, we will assume that our myCred installation has hooks which deduct points from users, creating the possibility of user’s accounts going minus.

Requirements

  • Hooks that deduct points from users creating the possibility for users accounts to go minus.

Authenticate

For this feature we will need to hook into WordPress using the authenticate filter. This filter fires when the user has entered their username and password and clicked “Login”. Our filter will check the users point balance and if it is below zero, we will return an error message which will prevent the user from logging in. Place the following code snippet into your theme’s function.php file.

/**
 * Block Negative Balances
 * Stop users from logging into your website if they have a negative
 * myCRED balance.
 * @version 1.0
 */
add_filter( 'authenticate', 'mycred_block_negative_balances', 990, 3 );
function mycred_block_negative_balances( $user, $username, $password ) {

 	// Make sure myCred is installed
 	if ( ! defined( 'myCRED_VERSION' ) ) return $user;

 	// The point type we want to use
 	$type = 'mycred_default';

 	// Load myCRED
 	$mycred = mycred( $type );
 	$account = get_user_by( 'login', $username );

 	if ( isset( $account->ID ) ) {

 		if ( ! $mycred->exclude_user( $account->ID ) ) {

 		if ( $mycred->get_users_balance( $account->ID, $type ) < 0 )
 			return new WP_Error( 'mycred_negative', __( 'Account Closed' ) );

 		}

 	}

 	return $user;

}

Done

There you have it. It’s as simple as that. You can of course enter your own message to show users and as the commented in the code, you can change it to block users with zero points as well.

Completely disable the Transfer form CSS styling

This tutorial only works with myCRED 1.6.x versions.

Navigation:

  1. Description
  2. Requirements
  3. De-registration
  4. Done

Description

In this quick tutorial I will show you have you can disable the CSS styling of the transfer points HTML form. By default, the Transfer Add-on provides some very basic structural styling, relying on you to style it to fit your website. You can completely disable the CSS styling allowing you to re-structure the transfer form.

Requirements

  • The Transfer Add-on must be enabled for this.

De-registration

You can also disable styling by deregistering the mycred transfer style.

add_action( 'wp_enqueue_scripts', 'dbm_remove_transfer_style', 15 );
function dbm_remove_transfer_style()
{
	wp_deregister_style( 'mycred-transfer-front' ); 
}

Done

There you have it. It’s as simple as that.

 

Update

The previous filter has been removed as of version 1.0.8 as the de-registration of the style is a far better approach.

11