Add an AJAX like button to WordPress

An Ajax-powered like button is to provide a seamless and instant feedback mechanism to users. With traditional page reloading, when a user clicks the like button, the entire page refreshes, causing a noticeable delay and interrupting the user’s browsing experience.

By using Ajax, the like button can update the like count or status in real-time without the need for a page refresh.

Let’s start implement an AJAX like button in WordPress.

Enqueue scripts

function enqueue_like_button_scripts() {
	wp_enqueue_script( 'jquery' );
	wp_enqueue_script( 'like', get_template_directory_uri() . '/js/like.js', array( 'jquery' ), '1.0', true );
	wp_localize_script(
		'like',
		'ajax_object',
		array(
			'ajax_url' => admin_url( 'admin-ajax.php' ),
			'nonce'    => wp_create_nonce( 'ajax-nonce' ),
		),
	);
	wp_enqueue_style( 'like', get_template_directory_uri() . '/css/like.css', array(), '1.0', 'all' );
}
add_action( 'wp_enqueue_scripts', 'enqueue_like_button_scripts' );

Enqueuing Scripts and Styles: The enqueue_like_button_scripts() function is used to enqueue the required scripts and styles. It includes the jQuery library, the like.js script for handling the like button functionality, and the like.css stylesheet for styling.

The wp_localize_script() function is used to pass necessary data to the JavaScript file, such as the Ajax URL and a nonce for security.

Display the like button

function like_button( $content ) {
	$like_count = get_post_meta( get_the_ID(), 'like_count', true );
	$like_text  = $like_count === 1 ? 'Like' : 'Likes';
	$liked      = isset( $_COOKIE[ 'like_' . get_the_ID() ] ) ? 'liked' : '';
	$nonce      = wp_create_nonce( 'ajax-nonce' );
	$like       = '<button class="like-btn ' . $liked . '" data-nonce="' . $nonce . '" data-post_id="' . get_the_ID() . '"><span class="like-count">' . $like_count . '</span><span class="like-text">' . $like_text . '</span></button>';
	$content    = $like . $content;
	return $content;
}
add_action( 'the_content', 'like_button' );

Displaying the Like Button: The like_button() function is hooked into the the_content action and modifies the content of the post. It retrieves the like count for the current post and generates the HTML markup for the like button.

The button is rendered with a class of liked if the user has already liked the post. The generated HTML is added before the post content.

Handling of the AJAX request

function like_button_ajax() {
	$nonce = $_POST['nonce'];
	if ( ! wp_verify_nonce( $nonce, 'ajax-nonce' ) ) {
		wp_send_json_error( 'Nonce is invalid' );
	}
	$post_id    = $_POST['post_id'];
	$liked      = isset( $_COOKIE[ 'like_' . $post_id ] ) ? true : false;
	$like_count = get_post_meta( $post_id, 'like_count', true );
	if ( ! $liked ) {
		$like_count++;
		update_post_meta( $post_id, 'like_count', $like_count );
		setcookie( 'like_' . $post_id, $post_id, time() * 20, '/' );
	}
	$like_text = $like_count === 1 ? 'Like' : 'Likes';
	wp_send_json_success(
		array(
			'count' => $like_count,
			'text'  => $like_text,
		),
	);
}
add_action( 'wp_ajax_nopriv_like_button_ajax', 'like_button_ajax' );
add_action( 'wp_ajax_like_button_ajax', 'like_button_ajax' );

Handling the Ajax Request: The like_button_ajax() function is responsible for handling the Ajax request made when the like button is clicked. It verifies the nonce for security, retrieves the post ID and like count from the request data, increments the like count if the post has not been liked before, updates the like count meta, and sets a cookie to remember the user’s like. Finally, it sends a JSON response with the updated like count and text.

JavaScript Code

jQuery(function($){
    $('.like-btn').click(function(){
        let post_id = $(this).data('post_id');
        let likeBtn = $(this);
        $.ajax({
            type: 'POST',
            url: ajax_object.ajax_url,
            data: {action: 'like_button_ajax', 'post_id': post_id, 'nonce': ajax_object.nonce},
            success: function(result){
                likeBtn.find('.like-count').text(result.data.count);
                likeBtn.find('.like-text').text(result.data.text);
                likeBtn.addClass('liked');
            }
        });
    });
});

When the button is clicked, an Ajax request is sent to the server. Upon success, the like count and text are updated, and the button is given the class liked to indicate that the user has liked the post.

Full code

functions.php File.

function enqueue_like_button_scripts() {
	wp_enqueue_script( 'jquery' );
	wp_enqueue_script( 'like', get_template_directory_uri() . '/js/like.js', array( 'jquery' ), '1.0', true );
	wp_localize_script(
		'like',
		'ajax_object',
		array(
			'ajax_url' => admin_url( 'admin-ajax.php' ),
			'nonce'    => wp_create_nonce( 'ajax-nonce' ),
		),
	);
	wp_enqueue_style( 'like', get_template_directory_uri() . '/css/like.css', array(), '1.0', 'all' );
}
add_action( 'wp_enqueue_scripts', 'enqueue_like_button_scripts' );

function like_button( $content ) {
	$like_count = get_post_meta( get_the_ID(), 'like_count', true );
	$like_text  = $like_count === 1 ? 'Like' : 'Likes';
	$liked      = isset( $_COOKIE[ 'like_' . get_the_ID() ] ) ? 'liked' : '';
	$nonce      = wp_create_nonce( 'ajax-nonce' );
	$like       = '<button class="like-btn ' . $liked . '" data-nonce="' . $nonce . '" data-post_id="' . get_the_ID() . '"><span class="like-count">' . $like_count . '</span><span class="like-text">' . $like_text . '</span></button>';
	$content    = $like . $content;
	return $content;
}
add_action( 'the_content', 'like_button' );

function like_button_ajax() {
	$nonce = $_POST['nonce'];
	if ( ! wp_verify_nonce( $nonce, 'ajax-nonce' ) ) {
		wp_send_json_error( 'Nonce is invalid' );
	}
	$post_id    = $_POST['post_id'];
	$liked      = isset( $_COOKIE[ 'like_' . $post_id ] ) ? true : false;
	$like_count = get_post_meta( $post_id, 'like_count', true );
	if ( ! $liked ) {
		$like_count++;
		update_post_meta( $post_id, 'like_count', $like_count );
		setcookie( 'like_' . $post_id, $post_id, time() * 20, '/' );
	}
	$like_text = $like_count === 1 ? 'Like' : 'Likes';
	wp_send_json_success(
		array(
			'count' => $like_count,
			'text'  => $like_text,
		),
	);
}
add_action( 'wp_ajax_nopriv_like_button_ajax', 'like_button_ajax' );
add_action( 'wp_ajax_like_button_ajax', 'like_button_ajax' );

like.js file

jQuery(function($){
    $('.like-btn').click(function(){
        let post_id = $(this).data('post_id');
        let likeBtn = $(this);
        $.ajax({
            type: 'POST',
            url: ajax_object.ajax_url,
            data: {action: 'like_button_ajax', 'post_id': post_id, 'nonce': ajax_object.nonce},
            success: function(result){
                likeBtn.find('.like-count').text(result.data.count);
                likeBtn.find('.like-text').text(result.data.text);
                likeBtn.addClass('liked');
            }
        });
    });
});

like.css file

.like-btn .like-count {
    margin-right: 5px;
}

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top