Atomic Smash homepage splash

Create a Like Post Button in WordPress

Words by Adam WardDecember 3, 2017

In this post, I will walk you through the process of creating your own like post button in WordPress. Here’s a demo of how my final button looks and functions…

See the Pen Like Button by Adam Ward (@wardadam1) on CodePen.

What we will use

Advanced Custom Fields – to create a custom ‘like’ number field
WordPress Rest API – to create a custom endpoint
jQuery – to handle the AJAX call and interactivity of the button.

Quick summary of how it will work

The button will appear at the bottom of our single post template, displaying the current number of likes. When a user clicks the button, we will trigger a jQuery click function, which in turn will make an AJAX call to the WP API endpoint. The endpoint will return true and update the custom field value by + 1. Using jQuery, we will disable the button so the user cannot ‘like’ again, unless they refresh the page.

Don’t worry, we will run through each step in more detail!


Step 1 – Create the custom field

Firstly, you will need a WordPress project setup with the, hugely popular and free, Advance Custom Fields (ACF) plugin installed. Using this plugin we will create a new custom field called ‘Likes Number’.

It will be a ‘number’ type field and I have put mine in a field group called ‘Single Post – sidebar’. The reason I appended ‘sidebar’ to the field group name is because I have set the ‘Position’ on the group to ‘side’. We often do this at Atomic Smash for groups that are more for post options and to separate them from the post’s main content fields.

Next, we need to output the number on to the single.php template. To test the new field, edit one of your posts and add the number 20, in to the new field. Then add this line of code to your single.php template, after the content…

<?php the_field('likes_number'); ?>

’20’ should now be output on your single template page.


Step 2 – Setup API route and callback function to update the likes number

If you haven’t used the WordPress REST API yet, you should start now! There are so many things you can do with it and today we will run through one of the most useful, in my opinion. We will create an endpoint, with a callback function, which will update our new custom field value.

New to the WordPress REST API?

Read Anthony's 2 part series on getting started with the WP REST API.

Read More

Firstly, we will create our new route – you could put this in your functions.php or in a new file called rest-api.php somewhere in your theme and then include it in your functions.php file.

// Register the new route
add_action( 'rest_api_init', function () {

  register_rest_route( 'example/v2', '/likes/(?P<id>\d+)', array(
        'methods' => array('GET','POST'),
        'callback' => 'example__like',
    ) );

});

Registering the route essentially creates an endpoint url, which you can send information to. After registering the route above, you should now be able to visit “http://yourwebsite.dev/wp-json/example/v2/likes”, it will say there’s “no route”, this is because we are missing the last part, which is a parameter called ‘id’, that’s the “(?P\d+)” part of the route above. The reason it is in this format in the route is because it’s a dynamic property, so you could send any ID number to the endpoint url.

This part of the new route – ‘ ‘callback’ => ‘example__like’ means we need to create a function called ‘example__like’. Essentially all we are saying here is, here’s a new endpoint url, when you hit this url, run this function.

Next, lets create the ‘example__like’ function.

// This is how you setup a callback function to work with your new endpoint
function example__like( WP_REST_Request $request ) {
    
        $likes = 20;
    
        return $likes;
    }

If you now visit the endpoint again and put a fake ID number at the end, like this –
“http://yourwebsite.dev/wp-json/example/v2/likes/2”

you should see that ’20’ is returned. This means our callback function is working!

Next we need to make the function return the number of likes for a post. This is where the ‘ID’ parameter comes in.

    function example__like( WP_REST_Request $request ) {
        // Custom field slug
        $field_name = 'likes_number';
        // Get the current like number for the post
        $current_likes = get_field($field_name, $request['id']);
        // Add 1 to the existing number
        $updated_likes = $current_likes + 1;
        // Update the field with a new value on this post
        $likes = update_field($field_name, $updated_likes, $request['id']);

        return $likes;
    }

In the updated function above, the ‘$request[‘id’]’, refers to the ID parameter we setup in the route. To test this get the post ID of the post you updated the likes number field to ’20’ earlier and use this ID at the end of the endpoint url. It should return ‘true’. This means the function has worked, if you go to edit the same post again you should notice it’s now updated to ’21’. Each time you visit this url it will plus 1, which means we now need to get the like button click to hit this url and trigger the same action.


Step 3 – Add jQuery functionality

Now we need to set up a user interaction to send an AJAX call to the new endpoint.

First, lets create our ‘like’ button.

<button class="like__btn">
    <span class="like__number"><?php the_field('likes_number'); ?></span>
</button>

Now lets add a click function in jQuery

// When a user clicks the like button
$('.like__btn').on('click', function(){
        // AJAX call goes to our endpoint url
        $.ajax({
            url: 'http://yourwebsite.dev/wp-json/example/v2/likes/7',
            type: 'post',
            success: function() {
                console.log('works!');
             },
             error: function() {
                console.log('failed!');
              }
          });
        
        // Change the like number in the HTML to add 1
        var updated_likes = parseInt($('.like__number').html()) + 1;

        $('.like__number').html(updated_likes);
        // Make the button disabled
        $(this).attr('disabled', true);
    });

This will work but we need to make the AJAX url dynamic. It’s currently set to ‘7’ at the end, which means it will only update the field on the post with the ID of 7. To make this dynamic we can make use of the ‘wp_localize_script‘ function, this allows us to pass information between PHP and Javascript.

If you put the following snippet in the function where you are registering your scripts in WordPress, it will be enqueued with the rest of your scripts and will make these variables available in Javascript.

wp_localize_script( 'init', 'bloginfo', array(
    		'template_url' => get_bloginfo('template_url'),
    		'site_url' => get_bloginfo('url'),
            'post_id'   => get_queried_object()
    	));

// 'bloginfo' is now an object and we can define what's available inside of it
// now we can access the template and site urls and the post ID
// we no longer need to worry if any of them were to change

We can now access the ‘bloginfo’ object in our Javascript, lets test it by logging them out in our console

// get the whole object
console.log(bloginfo);
// get the site url
console.log(bloginfo.site_url);
// get the current queried post ID
console.log(bloginfo.post_id.ID);

Now using this we can make our AJAX url dynamic.

// OLD
url: 'http://yourwebsite.dev/wp-json/example/v2/likes/7',

// NEW
url: bloginfo.site_url + '/wp-json/example/v2/likes/' + bloginfo.post_id.ID;


Step 4 – Adding the finishing touches!

Hopefully you have got to this point and it’s all working for you – now to add some finishing details. In the Codepen example at the top, I used this heart from the Font Awesome library, but there’s a ton of other free icon fonts out there. At Atomic Smash we tend to use the excellent Icomoon, as it easily allows you to combine lots of different libraries and your own icon fonts in to one stylesheet.

Next, we might want to add some animation to the button click, again like I have done in the Codepen example at the top. I used the animate.css library for this. You can see how this effect is achieved by looking at my Codepen example – after we set the button to disabled we then add the animation class like so –

// Make btn disabled
  $(this).attr('disabled', true).addClass('tada');

Just make sure the button already has the ‘animated’ class on it beforehand, as this class is required for the animate.css animations to work.

Wrapping up!

I have touched on quite a few techniques within this post and also shared some insights in to our preferred methods at Atomic Smash. I hope you found this walk through useful, if you had any problems following along please feel free to drop me an email.

Profile picture of Adam Ward

Adam WardDeveloper

Adam is an expert in WordPress development and CRM integrations. His ability to craft WordPress to a users needs makes our websites easier to use.

Go back to top

Keep up to date with Atomic news