A simple referral program awarding points

Home / Tutorials / 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!

http://mycred.me/?ref=ybro12

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.

  1. How would it be possible to do that not only for visits, but for user registrations as well? I mean, user gets 1 point for each visit it referral link will generate. And how would it be possible to do so, that he would get 10 for example for every registration will happen though his referral ID?

    1. You would need to adjust the “Detection” script for that. In my opinion, the easiest solution would be to use cookies.

      The example used in this tutorial, we redirect the user once the referral has been awarded in the “Detection” script. Before we re-direct, you would need to set a cookie for the current user. Then during registrations, check if the user has this cookie and award points accordingly.

      All though if memory serves me right, you need to set cookies just before you start rendering your themes output so for example the first thing in your header.php file as doing it on ‘wp’ might be to early.

    2. That was too difficult explanation for me as I don’t have almost any kwolwedge with coding 🙂 But thanks for your efforts Gabriel.

      Btw, is it very difficult to include general hooks ir an add-on with those features (I mean points for visits and points for registrations)?

  2. Hi Gabriel,

    Thanks a lot for helping. I think that is really very important feature, which more and more members, who download this plugin will ask. Together with this features this plugin would be just perfect!

    1. Hey Sam.

      I will look into converting this into a simple plugin for you. I am however not sure it would be something I would release anywhere but here since it is very basic and do not have the time right now to support.

  3. This is a great script for what our site is using. However, I have a few questions about this. Does the person who signs up through a referral link get points? And secondly, is there a way to use shortcode to display the referral link every time the shortcode is mentioned in WordPress? Thank you in advance.

    1. I think you might have missed the “Update” section of this tutorial. I added in an example of how to add points to those who signup using a referral link.

      Not sure I understand “every time the shortcode is mentioned in WordPress”.

    2. Whenever you place a shortcode in a WordPress page or post, WordPress will find the shortcode and replace it with content. I would like the script to capture a user’s referral URL and then replace a shortcode with that URL wherever it is placed.

  4. Hi, can someone explain me where to add that code? I’ve added it in the functions.php theme and it seems it won’t do anything. I’m new in this area and i dont know very much about coding.

    Can someone explain me step by step what to do to make this work? I’m doing a giveaway on my site and I want the users that participate to the giveaway to share it and get 1 point on every unique visit and 10 points on every people invited to register to the giveaway.

    Any ideeas?

    Thanks in advance, you do a great work guys!

  5. Hi Gabriel,

    this is working quite well. Only problem is, that somehow when the same person clicks m ref links twice I’m getting the 1 Ticket per visitor twice. Is there something missing in the code that’s proving the ip or stores it for some time?

    Best regards, Lars

    1. If you have issues with the IP address, I would suggest that you test and see how IP addresses are handled. The IP is saved in the data column when the user gains points and is checked by has_entry(). However the above code is very straight forward and only checks to make sure the IP address is not empty.

  6. I really know nothing about programming, however I managed to get the referral program to work. Even figured out the update after a few tries. I am unclear on how to go about placing the referral links on a page other than the users profile.

    Do I simply need to add the url that I want it to show on in the quotes or is there more to it.
    I am using the S2Member Plugin and have blocked the WP Profile page to provide added security. The S2Member Profile for members is added to a page with a shortcode.

    Is there a possibility of there being a shortcode for this? Is there a MyCred for dummies as I believe that’s what I need…..

    Your plugin is awesome, but would be even more awesome if it had an addon, hook or plugin for this. You know, one of those deals in the WP Admin Panel. It’s one that I would definately purchase.

    Can you also direct me to the shortcodes that are available. I can’t seem to locate them.

    Great Job and many thanks,
    Wayne Caviness

    1. Hey Wayne.

      I am adding a custom hook in myCRED 1.4 that will do what this tutorial does with a few additional options.

      Now regarding displaying the link, you can either display it by adding it into the appropriate theme file or create a custom shortcode that you can use in the content. Using your theme would for example allow you to always show at the bottom of the content the referral link for logged in users.

      Example: Insert the following under <?php the_content(); ?> in your template file:

      <?php if ( is_user_logged_in() ) : ?>
      echo 'Get points by referring viewers for this post by using the following link: ' . mycred_get_ref_for_url( get_permalink() );
      <?php endif; ?>
      

      The above code will then if the user is logged in, show the text with the post permalink to the current post. The current users referral ID would be appended to this link.

      In what exact theme file the above codes goes into depends on your theme. Some themes use content.php or content-post.php for displaying the post content while others just use single.php. The main thing to remember is that the above code must be places inside the loop since we are using the get_permalink() function.

  7. Its a very smat way to promote your website. I have been looking for this feature specially “A simple referral program awarding points” for so long. I have installed myCred but still dont know how to add this feature. Help showing how to add this feature will be highly appreciated.

    1. Hi. If you look at the the beginning of the tutorial, you will see that you are to paste this into your functions.php file. You will then need to show your users their referral links which this tutorial inserts into your users profiles.

  8. Great plugin in general.
    I added the code in functions.php, and visited the referral url (domain.com?ref=SgeG%25%28) from a unique IP.
    However, credit is not added to the account.

    I would really love if this would work.

    Thanks.

    1. Hey.

      Check what is saved as reference in your database with each log entry. See if an IP address is actually saved each each new entry.
      Make sure $_SERVER[‘REMOTE_ADDR’] returns your IP address on your server.

  9. I can’t find anything in the database.
    REMOTE_ADDR works fine. It returns my IP address as it should.

    Something that feels weird, is the referral url generated (domain.com?ref=SgeG%25%28). Should it really look that way?

    Thanks for the quick response.

    1. Hey Josh.

      Originally I hoped that 1.4 Beta could be out by end of January but due to lack of sales I have had to prioritise development work in order to fund further development. Right now I am hoping to have the beta out mid to end of February.

    1. Looks very promising. I appreciate the hard work.
      I will definitely buy addons.

      Ideas:
      – Receive credit as a guest. In the notification, could say: You received 50 credits. Login to claim it.
      – Credits for updating content.
      – Credits for an actual FB share/like (is this even possible?)

    2. Hey John.

      To give points to visitors, you will need to identify and store each visitors points. One way to do this would be by using Cookies that holds a users points until they signup. Of course this will not work if the user has Cookies disabled.

      I know someone who is working on a solution for this.

      Regarding points for updates, that is pretty easy to do however the question is what qualified an update? Just clicking on the Update button without any changes to the content? This can be done and enforced in a lot of different ways, depending on what you are looking for.

      In order for you to give points for “actual” FB shares, you will need to use an Application that informs your site of your users actions. Your users will need to install this app in order to get points. Unfortunately I do not provide support for FB Apps.

  10. What would I need to edit in the detect script, to award points to for every click? that way a unique IP isnt needed? That way User A, can get credit for each of Guest 1’s clicks.

    1. You would need to remove the IP check in the script but without it, you open yourself for possible abuse where users just mass click to gain points. Always good to enforce some limits.

  11. So just remove the: “$IP = $_SERVER[‘REMOTE_ADDR’];
    if ( empty( $IP ) ) return;”

    and end with

    $mycred = mycred_get_settings();
    if ( ! $mycred->has_entry( ‘visitor_referring’, ”, $user_id ) )

    ??

  12. What does it mean if the code you shared here appears in plain text at the header of my site?
    I originally got no errors, yet no referal ID was integrated into the URL in the address bar (am I mistaken about that?) and upon going to the Dashboard I got php errors pointing to the code that inserts the link into the template. I removed all instances of that as it showed error for each one in succession. Then after removing all of them, the functions code displays in the header.

    Thanks

    P.S. The them I’m using hasn’t been maintain for 4 years. And no, I’m not changing it for a new one. All the new themes in the repository these days suck.

    1. I am not sure I understand what the issue is. The code in this tutorial goes into your themes functions.php file and nowhere else. If you have copied the code correctly (the entire code) then this should bring no issues. The only issues I could see is if you are using an old WP version. The above code required at least WP 3.1.

      The referral link is “visible” in the sense that a user can see it as it is appended to the end of a URL, i.e. http://yoursite.com/?ref=123456. But the same goes for most referral scripts.

  13. Hello Gabriel,

    thanks for your code and the tutorial.

    However, have a little problem!

    I added the code in functions.php, and visited the referral url from a unique IP.
    However, credit is not added to the account.

    I have checked the database table “my_CRED_Log” and it ist empty!
    And i checked the “$_SERVER[‘REMOTE_ADDR’]” and it´s work fine.

    Can you say me what is the Problem or what make it wrong??

    Thanks for your effort.

    PS:When comes out the version 1.4?

    1. I would start by enabling WP_DEBUG and see if there are any error messages when you try to use this feature.

      I am working on a project right now to help fund further development of myCRED and should be done in one or two weeks time. So I am aiming at end of February.

    2. Hello Gabriel,

      ok! I have start WP_DEBUG an i became 2 errors on the Site from a other plugin!

      I have fix the errors!

      The Problem is the same! No entries on the Log files! What yet?

  14. Hi Gabriel,

    Ok!

    I can´t find the problem!

    I have install the myCred Plugin on a fresh WordPress Installation and have activate the WordPress Theme “Twenty Fourteen”. No other Plugins install or run!

    The Code for the “simple referral Programm” have copy and paste from this post to the functions.php.

    I have activate “WP_DEBUG” no errors!

    Ok! Yet i have testing with a new IP.

    Sorry. No entries at the log table “myCRED_log”!

    I can not unterstand that! What i make wrong??

    1. Hello Gabriel,

      i have found the Problem!

      I have search all day in the code, and have yet found the problem.

      Ok here the problem.
      This code snippet is the problem {$wpdb->usermeta},
      when i delete this snippet and insert my real table name than it is running perfectly.

  15. I have followed this instruction and successfully added the complete code to my functions.php but I am not able to figure out how to add the ability to show page visitors ie members their referral link with ID. Id like to add it to my homepage so that it shows as follows:

    Refer users to our website and earn points!

    http://mycred.me/?ref=ybro12

    how do I do so?

  16. Hi!

    I’m a beginner with worpress, so please forgive me if I will ask something what is very simple for others.

    I use myCRED and I want to implement this update ” add points when users signup using this referral system” , and I can handle to insert that code. Where I must to put the code (in wich files inside the wordpress) ? I must to copy just that 2 parts under “Update”? And where can I set how many points get the users for sign up of their referrers.

    And can I show the referrers under the widget “My Points”?

    Thanks in advance!

    1. Hi George. If you are using myCRED 1.4 or higher, this hook has been included in the plugin code and you do not need to use this. Please remove the code you have pasted in to your themes functions.php file (if you have) and visit the myCRED > Hooks page where you now have a new hook called “Points for referrals”.

  17. Thank you for your reply.

    I found it. I just upgrade to the last myCred and this hook is just there.

    I want to implement if is possible 2 more features, but I’m not a good php programer, not even with wordpress.
    The first one I want to show for every user how many referrals have (registered after referral link) and which they are (users).

    The second one: If User A have 2 referrals User 1 and User 2, if User 1 add a comment or post User A get 1point, the same for User B.

    Thanks in addvance!

    Best regards,
    George Barbu
    (+4) 0727-971.215

  18. Would there be a way for a user to get points once their referred user gain a certain amount of points? For example:

    Person A refers Person B to the site and Person B uses the referral code provided by Person A. Can I make it so Person A only get points once Person B reaches a number of points on the website? I want to prevent people from gaming.

    Thanks. I hope this makes sense. If not I can rephrase the question. 🙂

    1. Hi Damon.

      There are several ways this could be done. If you post your question in the support forum I can offer some code examples. The comment section unfortunately does not handle code well.

  19. Gabriel,
    This is awesome!! Thank you for creating that detection script. It works great for me. I was just curious though if I still wanted the user to have the option to provide the link as well do I just add all the original script that you created for awarding link clicks? I just wanna know if they will both work together. Thanks!

    Clint,

    1. Actually it doesn’t work. I tried it by itself and together and it doesn’t work. When I add both together my site stops working. When I add just the script for the affiliate link my website works but its not displaying the link on my edit profile page. Can you please help me with this?

    2. Hey. Yeah this will not work if you are using myCRED 1.6 or higher. This tutorial was meant for users who are still on myCRED 1.3 or lower. In 1.4, the Points for referral hook was introduced which you should be using instead.

    3. @Gabriel is there a way to get the older verison on Mycred so I can get this to work on the website? Or can you update it?

  20. Hello Gabriel (@unimatrix0),
    I am struggling to get the “Points for referral” hook working.

    I am using myCRED 1.6.6 and whenever we click on the referral
    link, it leads to a “page not found” page.

    Dont know what I am doing wrong. Ideally, it should lead to a
    landing page or the register page so that the invited user could
    register to the site.

    What am I doing wrong?

    Thanks in advance.

    1. Can you show me an example of a URL that does not work (so we can start by looking at the URL to make sure it is correct).

      Please remember that this referral tutorial will not work with myCRED 1.6 or higher as based on this tutorial I actually built a referral system and included it into myCRED.

  21. It would be great if you could point me to some tutorial, or whatever, to show adding points for referred user sign ups works in your current system.

    I’m definitely interested in using this system for a new project, but to be honest, with a lot of other things I have to do, I need to be able to ascertain if this can be done easily or not.

    thanks.

Leave a Reply

Last edited December 1, 2015