How to Create a WordPress Reward for Tweet Plugin

Posted in Coding, Tutorials, WordPress • Posted on 13 Comments

As a website owner or blogger you need a good number of subscribers and followers to be successful in the social media world. Many websites provide freebies such as eBooks, Icon Packs and Plugins in exchange for emails. Getting people to tweet your content is another trending method to get more visitors to your site. In this tutorial, I’ll be showing how to create a WordPress reward for Tweet plugin to increase the tweets on your content while satisfying everyone!

Basically we are going to provide rewards for users who tweet our content. You will be able to provide a freebie for each of your blog posts or tutorials. Once the user tweets the content, the download link will be shown to the users. You can provide related links, tutorial files, link for a special offer as a reward, and so on.

Download? See the demo!

Creating the Plugin Files

First thing we have to do is create a folder called Reward-Tweets in the wp-content/plugins directory and create the index.php file inside the folder. Once it is done we need to provide the information about the plugin on the top of the index.php file using comments as shown in the code below.

/*
 Plugin Name: Reward for a Tweet
 Plugin URI: http://innovativephp.com/
 Description: Provide additional links or freebies for a tutorial for tweeters.
 Version: 1.0
 Author: Rakhitha Nimesh
 Author URI: 
 License: GPLv2 or later
*/

Now you will be able to see the plugin on your admin dashboard with the link to activate the plugin.

Adding Reward for Tweet Link to Posts

Each post is going to have its own reward link. You can omit the reward link if you don’t have anything to provide for a specific post. So first thing we need to do is to add a textbox to the post creation screen to insert reward links.

Adding Meta Boxes to Post Screen

We can add custom fields using WordPress meta boxes. Consider the code below.

add_action('add_meta_boxes', 'add_reward_link_box' );
function add_reward_link_box()
{
    add_meta_box( 'reward_link_box-id', 'Reward Link', 'display_reward_link_box', 'post');
}
  • We can create a custom meta box using the add_meta_box function inside the add_meta_boxes action.
  • First parameter is a unique ID for the meta box.
  • Second Parameter is the title of the meta box. I have named it as Reward Link.
  • Next parameter is the function name which is used to display the HTML for metabox.
  • Fourth parameter is the post type. Since we are using normal posts it will be post. You will have to change this if you are using reward links on custom post types.

Now we can take a look at display_reward_link_box function which is used to display the custom fields.

function display_reward_link_box(){
    global $post;
    $values = get_post_custom( $post->ID );
    $reward_link = isset( $values['reward_link'] ) ? esc_attr( $values['reward_link'][0] ) : '';

    wp_nonce_field( 'reward_link_box', 'reward_link_box' );

    $html = "<lable>Reward Link</label><input type='text' name='reward_link' value='$reward_link' />";
    echo $html;
}
  • Initially we get all the custom meta values related to the current post using get_post_custom function.
  • Then we check whether Reward Link exists for the current post using the received post meta values. If a link is already available we insert it as the value of text field.
  • Next we create a WordPress nonce value using wp_nonce_field function. This will be used to validate the request when we hit the publish button. Provide a unique key for the parameters of this function.
  • Finally we display the HTML label and text field for our Reward Link.

If you configured everything correctly up to now, you should be able to see the meta box with Reward Link field in the bottom of the post creation screen after activation.

Saving Reward Link Value to Database

Now we have to save the value of the Reward Link once you hit the publish button and save the post. Following code will be used to save the data to wp_postmeta table.

add_action( 'save_post', 'reward_link_box_save' );
function reward_link_box_save($postID){

    if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;

    if( !isset( $_POST['reward_link_box'] ) || !wp_verify_nonce( $_POST['reward_link_box'], 'reward_link_box' ) ) return;

    if( !current_user_can( 'edit_post' ) ) return;

    if( isset( $_POST['reward_link'] ) )
       update_post_meta($postID, 'reward_link', esc_attr( $_POST['reward_link'] ) );

}
  • First we add a function called reward_link_box_save to be called after the post is saved to the database.
  • Current post ID will be passed automatically to this function after the post is saved.
  • WordPress has an autosave feature. We don’t want to save the reward link on autosave. So we check for auto save and return from the function.
  • Then we check whether the form is valid for the current request using the nonce value we created earlier and returns in case it is not valid.
  • Then we check whether the current user is allowed to edit posts.
  • Once all the above validations are successfully completed, we save the Reward Link with the key reward_link using update_post_meta function.

Now we have all the reward links for posts in database. In the next section I’ll explain how to create Tweet Button and provide rewards.

Configuring Styles and Scripts

We have to provide the necessary scripts and styles for the plugin using wp_enqueue_scripts action. Following code will add all the necessary scripts and styles.

function apply_reward_tweet_scripts() {
  global $post;

    wp_enqueue_script('jquery');

    wp_register_script("twWidget", "http://platform.twitter.com/widgets.js");
    wp_enqueue_script('twWidget');

    wp_register_script('rewardTweet', plugins_url('js/rewardTweet.js', __FILE__));
    wp_enqueue_script('rewardTweet');

    wp_register_style('rewardTweetStyles', plugins_url('css/rewardTweet.css', __FILE__));
    wp_enqueue_style('rewardTweetStyles');

    $config_array = array(
       'rewardAjaxUrl' => admin_url('admin-ajax.php'),
       'rewardNonce' => wp_create_nonce('reward-nonce'),
   'rewardPost' => $post->ID
    );

    wp_localize_script('rewardTweet', 'rewardData', $config_array);

}
add_action('wp_enqueue_scripts', 'apply_reward_tweet_scripts');
  • First we call the apply_reward_tweet_scripts function to enque scripts.
  • Inside the function we include jquery and Twitter widget using wp_enqueue_script function. wp_enqueue_script is the recommended way of inserting scripts securely in WordPress.
  • Twitter widget.js file is required for generating the tweet button and styles.
  • Then we include custom js script called rewardTweet.js and custom styles called rewardTweet.css to define our plugin functions and styles.
  • Finally we define some values we need inside the js script in the $config_array. Ajax URL will be the admin-ajax.php file of WordPress. Nonce value is used to validate the request and current post ID.
  • Then we use wp_localize_script to add the above values to the js file.First parameter is the name used to include the custom js using wp_enqueue_script.
  • Second parameter will be the name of the object which will be used to access data and the third parameter is the array of values to be included.

Next we have to display the tweet button on each post. Let’s move onto displaying tweet button.

Display Tweet Button

We have already included the scripts for getting the tweet button. Now we have to include the link which generates the tweet button. Code given below will insert the Tweet button to your posts.

function add_reward_tweet_button($content){
	global $post;

	$tweet_meta_values = get_post_meta($post->ID,'reward_link');

	$tweet_text = $post->post_title." - ".get_site_url();

	if(is_single() && isset($tweet_meta_values[0]) && $tweet_meta_values[0] != '' ){
		return $content."<div class='tw_reward_panel' ><div class='tw_reward_title'>Tweet and Get Rewarded
<span class='tw_reward_button'><a href='https://twitter.com/share?text=$tweet_text&via=1stwebdesigner' class='twitter-share-button' data-lang='en'  data-url='$post->guid'  >Tweet</a></span></div>
<div class='tw_reward_links'><a id='rewardLink' href=''>Click Here To Get Reward Link</a><div style='clear:both'></div></div></div>";
	}else{
		return $content;
	}

}
add_filter('the_content','add_reward_tweet_button');
  • Initially we call the add_reward_tweet_button function on the_content filter. This filter will be applied for content of every post and page.
  • Page or post content will be automatically passed to this function.
  • Then we get the custom meta values of the current post.
  • We don’t want to include this Reward Link in summary, category, archive, tag pages. We call the function is_single to ensure that this is the detailed post page.
  • Also we check whether Reward Link exists for current post and display the tweet button.
  • Reward Panel will not be visible if the post does not have a reward link.

Now you should be able to see the Reward Panel under each post with a reward link as shown in the screen below.

Reward Links Before Tweet

Provide Download Links On Tweet

Now once the tweet button is clicked and tweet is published on user’s profile, we need to display the Reward Link. We are going to use Twitter Web Intents Events to identify the end of a tweet. You can find more information about Twitter events on the Twitter Dev center. So let’s create the JavaScript code in the rewardTweet.js file to handle the Reward Link display after tweet is published.

   $jq =jQuery.noConflict();

   twttr.events.bind('tweet', function(event) {
      $jq.post(rewardData.rewardAjaxUrl, {
               action:"get_reward_links",
               nonce:rewardData.rewardNonce,
       postID :rewardData.rewardPost
       }, function(result, textStatus) {

       if(result.status == 'success'){
           $jq("#rewardLink").attr("href",result.value);
           $jq("#rewardLink").show();
       }

           }, "json");

       });
  • First line will prevent jQuery from being conflict with other libraries.
  • Next we use twttr.events.bind(‘tweet’, function(event) to bind a custom function to our Tweet button. This function will be executed once user publishes a Tweet.
  • Inside the function we are using rewardData object to get the data which we inserted to the script using wp_localize_script.
  • Next we use an action called get_reward_links for the AJAX request. Using the action in WordPress will be explained in the next section.
  • Once the request is successfully completed you will get a JSON object containing the reward link.
  • We check the status of the result and assign the Reward Link to the Download button and display it to the user.

Final part of this plugin will be to handle the above AJAX request and generate the Reward Links, which will be discussed next.

Generating Reward Link

We send the AJAX request to the server with current post ID. Consider the code below for complete implementation.

function get_reward_links(){
	global $post;

	$tweet_meta_values = get_post_meta($_POST['postID'],'reward_link');
	if(isset($tweet_meta_values[0]) && $tweet_meta_values[0] != '' ){
		echo json_encode(array("value"=>$tweet_meta_values[0],"status"=>"success"));exit;
	}else{
		echo json_encode(array("status"=>"error"));exit;
	}

}
add_action('wp_ajax_nopriv_get_reward_links', 'get_reward_links');
add_action('wp_ajax_get_reward_links', 'get_reward_links');
  • First we use the action defined in previous section and configure the AJAX requests handling function using wp_ajax_nopriv_get_reward_links and wp_ajax_get_reward_links.
  • wp_ajax_nopriv is used for users who are not logged into the site.
  • wp_ajax is used for users who are logged into the site.
  • Inside the get_reward_links function we get the reward link for the current post and sends it back to browser with status in JSON encoded object.
  • Previous JavaScript code will decode the JSON object and display the Reward Links for the user.

Reward Link After Tweet

Now we have the completed Reward for Tweet plugin. You can easily insert rewards for each post in the admin dashboard and allow users to download once the tweet is completed. We hope this plugin helps you promote your website and gain newer visitors!

22 Written ArticlesWebsiteGoogle+

Rakhitha Nimesh is a software engineer and writer from Sri Lanka. He likes to develop applications and write on latest technologies. He is available for freelance writing and WordPress development. You can read his latest book on WordPress Web Application Development. He is a regular contributor to 1stWebDesigner, Tuts+ network and Sitepoint network. Make sure to contact him at www.innovativephp.com or follow him on Twitter and Google+

13 Comments Best Comments First
  • Michaela

    Tuesday, October 9th, 2012 12:07

    4

    Great article. I must do this!

    0
  • Mike Wagner

    Monday, October 8th, 2012 14:31

    2

    The plugin not working. :( I am seeing this message after activating it.
    The plugin generated 259 characters of unexpected output during activation. If you notice “headers already sent” messages, problems with syndication feeds or other issues, try deactivating or removing this plugin.
    please tell me what wrong I am doing, I really need this plugin working for my blog.

    0
    • Rakhitha Nimesh

      Tuesday, October 9th, 2012 20:07

      6

      Hi Mike

      I cannot find any issues since its working fine on the demo site. Can u please send a screenshot of what you get ?
      If possible check this plugin on a fresh WordPress installation. Some other plugins which you have already installed might have something to do with this error.

      0
  • matoweb

    Tuesday, October 9th, 2012 05:33

    3

    this is exactly what I was looking for months ago, but couldn’t find a simple and really useful solution. Thanks a lot for this.

    0
  • Mike Wagner

    Thursday, October 11th, 2012 14:25

    7

    Hello Rakhitha,
    The pluging is working now, I downloaded the plugin from the demo link you provided in the post, I think I did something wrong while creating the pluging by my own, anyway thanks for this awesome giveway,
    I wanted to ask you one more thing, how can I make the tweet to get reward section in the post to appear on top section of the post , the tweet to get reward is at the bottom of every post,
    please let me know I am looking forward to your reply
    thanks

    0
    • Rakhitha Nimesh

      Friday, October 12th, 2012 00:34

      8

      Hi Mike

      Go to the add_reward_tweet_button function and change the following code with this: http://pastebin.com/DEcZkTaH

      +1
      • Mike Wagner

        Friday, October 12th, 2012 02:31

        9

        Thanks for your help again, I will try to do it.

        0
  • Taavi

    Monday, October 8th, 2012 12:15

    1

    Awesome! Any chance you can show us how to do the same for facebook likes?

    0
    • Rakhitha Nimesh

      Tuesday, October 9th, 2012 20:05

      5

      Thanks for the comment. I’ll check whether Facebook provides similar API for this functionality.

      0
  • Adjie

    Saturday, November 24th, 2012 22:29

    13

    Excellent plugin, I’ve tested it and brilliant Idea!

    0
  • Nish

    Wednesday, October 31st, 2012 16:07

    12

    But wordPress already have plenty of small plugins that does exactly this + more, why go to the extend of doing all coding when you can simply click a button and install it from the WordPress repository ?

    0
  • sarah

    Tuesday, October 30th, 2012 00:43

    11

    what should I do if I want the visitor have to tweet and follow before the reward link appear?

    0
  • Aplicativos

    Monday, October 15th, 2012 15:06

    10

    awesome post!!! thank you

    0
  • Adjie

    Saturday, November 24th, 2012 22:29

    13

    Excellent plugin, I’ve tested it and brilliant Idea!

    0
  • Nish

    Wednesday, October 31st, 2012 16:07

    12

    But wordPress already have plenty of small plugins that does exactly this + more, why go to the extend of doing all coding when you can simply click a button and install it from the WordPress repository ?

    0
  • sarah

    Tuesday, October 30th, 2012 00:43

    11

    what should I do if I want the visitor have to tweet and follow before the reward link appear?

    0
  • Aplicativos

    Monday, October 15th, 2012 15:06

    10

    awesome post!!! thank you

    0
  • Mike Wagner

    Thursday, October 11th, 2012 14:25

    7

    Hello Rakhitha,
    The pluging is working now, I downloaded the plugin from the demo link you provided in the post, I think I did something wrong while creating the pluging by my own, anyway thanks for this awesome giveway,
    I wanted to ask you one more thing, how can I make the tweet to get reward section in the post to appear on top section of the post , the tweet to get reward is at the bottom of every post,
    please let me know I am looking forward to your reply
    thanks

    0
    • Rakhitha Nimesh

      Friday, October 12th, 2012 00:34

      8

      Hi Mike

      Go to the add_reward_tweet_button function and change the following code with this: http://pastebin.com/DEcZkTaH

      +1
      • Mike Wagner

        Friday, October 12th, 2012 02:31

        9

        Thanks for your help again, I will try to do it.

        0
  • Michaela

    Tuesday, October 9th, 2012 12:07

    4

    Great article. I must do this!

    0
  • matoweb

    Tuesday, October 9th, 2012 05:33

    3

    this is exactly what I was looking for months ago, but couldn’t find a simple and really useful solution. Thanks a lot for this.

    0
  • Mike Wagner

    Monday, October 8th, 2012 14:31

    2

    The plugin not working. :( I am seeing this message after activating it.
    The plugin generated 259 characters of unexpected output during activation. If you notice “headers already sent” messages, problems with syndication feeds or other issues, try deactivating or removing this plugin.
    please tell me what wrong I am doing, I really need this plugin working for my blog.

    0
    • Rakhitha Nimesh

      Tuesday, October 9th, 2012 20:07

      6

      Hi Mike

      I cannot find any issues since its working fine on the demo site. Can u please send a screenshot of what you get ?
      If possible check this plugin on a fresh WordPress installation. Some other plugins which you have already installed might have something to do with this error.

      0
  • Taavi

    Monday, October 8th, 2012 12:15

    1

    Awesome! Any chance you can show us how to do the same for facebook likes?

    0
    • Rakhitha Nimesh

      Tuesday, October 9th, 2012 20:05

      5

      Thanks for the comment. I’ll check whether Facebook provides similar API for this functionality.

      0

Comments are closed.

54.161.143.22 - unknown - unknown - US