Hướng dẫn tạo plugin nút like dùng ajax và meta box trong WordPress

Bước 1: vào thư mục wp-content/plugins tạo wp-content/plugins/like-post

Với like-post chính là tên plugin sẽ hiển thị trong cài đặt.

Tại thư mục like-post tạo file cấu hình sau:

Nội dung file: kaj_config.php

 

<?php
/**
* Plugin Name: Like Post
* Plugin URI: http://demo.com
* Description: Đây là plugin nhấn like cho bài viết
* Version: 1.0
* Author: Tui
* Author URI: http://demo.com
* License: GPLv2 or later
*/

if ( ! defined( ‘KAJ_FILE_LIKE_POST’ ) ) {
define( ‘KAJ_FILE_LIKE_POST’, __FILE__ );
}

/**
Khai báo meta box
**/
function kaj_like_post_meta_box()
{
add_meta_box( ‘kaj-like-post’, ‘Kaj Like Post’, ‘kaj_like_post_thongtin_output’, ‘post’ );
}
function kaj_like_post_thongtin_output()
{
// Load the IA plugin.
require_once dirname( KAJ_FILE_LIKE_POST ) . ‘/kaj_like_post.php’;
}

add_action( ‘add_meta_boxes’, ‘kaj_like_post_meta_box’ );

class Kaj_button_like_post {
public function __construct() {
// Load the plugin functions files.
add_action( ‘plugins_loaded’, array( &$this, ‘includes_Kaj_like_post’ ), 1 );
}

public function includes_Kaj_like_post() {
require_once dirname( KAJ_FILE_LIKE_POST ) . ‘/kaj_like_button.php’;
}
}
new Kaj_button_like_post;

?>

<?php // used here only for enabling syntax highlighting. Leave this out if it’s already included in your plugin file.

// Fires after WordPress has finished loading, but before any headers are sent.
add_action( ‘init’, ‘script_enqueuer’ );

function script_enqueuer() {

// Register the JS file with a unique handle, file location, and an array of dependencies
wp_register_script( “liker_script”, plugin_dir_url(__FILE__).’liker_script.js’, array(‘jquery’) );

// localize the script to your domain name, so that you can reference the url to admin-ajax.php file easily
wp_localize_script( ‘liker_script’, ‘myAjax’, array( ‘ajaxurl’ => admin_url( ‘admin-ajax.php’ )));

// enqueue jQuery library and the script you registered above
wp_enqueue_script( ‘jquery’ );
wp_enqueue_script( ‘liker_script’ );
}
?>

<?php // used here only for enabling syntax highlighting. Leave this out if it’s already included in your plugin file.
//Xử lý ajax dữ liệu
// define the actions for the two hooks created, first for logged in users and the next for logged out users
add_action(“wp_ajax_my_user_like”, “my_user_like”);
add_action(“wp_ajax_nopriv_my_user_like”, “please_login”);

// define the function to be fired for logged in users
function my_user_like() {

// nonce check for an extra layer of security, the function will exit if it fails
if ( !wp_verify_nonce( $_REQUEST[‘nonce’], “my_user_like_nonce”)) {
exit(“Woof Woof Woof”);
}

// fetch like_count for a post, set it to 0 if it’s empty, increment by 1 when a click is registered
$like_count = get_post_meta($_REQUEST[“post_id”], “likes”, true);
$like_count = ($like_count == ’) ? 0 : $like_count;
$new_like_count = $like_count + 1;

// Update the value of ‘likes’ meta key for the specified post, creates new meta data for the post if none exists
$like = update_post_meta($_REQUEST[“post_id”], “likes”, $new_like_count);

// If above action fails, result type is set to ‘error’ and like_count set to old value, if success, updated to new_like_count
if($like === false) {
$result[‘type’] = “error”;
$result[‘like_count’] = $like_count;
}
else {
$result[‘type’] = “success”;
$result[‘like_count’] = $new_like_count;
}

// Check if action was fired via Ajax call. If yes, JS code will be triggered, else the user is redirected to the post page
if(!empty($_SERVER[‘HTTP_X_REQUESTED_WITH’]) && strtolower($_SERVER[‘HTTP_X_REQUESTED_WITH’]) == ‘xmlhttprequest’) {
$result = json_encode($result);
echo $result;
}
else {
header(“Location: “.$_SERVER[“HTTP_REFERER”]);
}

// don’t forget to end your scripts with a die() function – very important
die();
}

// define the function to be fired for logged out users
function please_login() {
echo “You must log in to like”;
die();
}

?>

 

Nội dung file: kaj_like_post.php

// The ‘likes’ meta key value will store the total like count for a specific post, it’ll show 0 if it’s an empty string
<?php
global $post;
$likes = get_post_meta($post->ID, “likes”, true);
$likes = ($likes == “”) ? 0 : $likes;
?>

This post has <span id=’like_counter’><?php echo $likes ?></span> likes<br>
// Linking to the admin-ajax.php file. Nonce check included for extra security. Note the “user_like” class for JS enabled clients.
<?php
$nonce = wp_create_nonce(“my_user_like_nonce”);
$link = admin_url(‘admin-ajax.php?action=my_user_like&post_id=’.$post->ID.’&nonce=’.$nonce);
echo ‘<a class=”user_like” data-nonce=”‘ . $nonce . ‘” data-post_id=”‘ . $post->ID . ‘” href=”‘ . $link . ‘”>Like this Post</a>’;
?>

Nội dung file: kaj_like_button.php

<?php
class Kaj_like_post_button {

/**
* Constructor method
*
* @since 0.1.0
*/
public function __construct() {

// Adds the media button.
add_action( ‘media_buttons’, array( $this, ‘media_button_Kaj_like_post’ ), 20 );

}

public function media_button_Kaj_like_post( $editor_id = ‘content_Kaj_like_post’ ) {

// Check if the current screen is post base.
if ( ‘post’ != get_current_screen()->base ) {
return;
}

echo ‘<a href=”../editor/editor.php” target=_blank class=”button junkie-thicbox” title=”‘ . __( ‘Kaj Like Post’, ‘tj-shortcodes’ ) . ‘”>’ . __( ‘Kaj Like’, ‘tj-shortcodes’ ) . ‘</a>’;

}

}

new Kaj_like_post_button();

?>

Nội dung file: liker_script.js

jQuery(document).ready( function() {
jQuery(“.user_like”).click( function(e) {
e.preventDefault();
post_id = jQuery(this).attr(“data-post_id”);
nonce = jQuery(this).attr(“data-nonce”);
jQuery.ajax({
type : “post”,
dataType : “json”,
url : myAjax.ajaxurl,
data : {action: “my_user_like”, post_id : post_id, nonce: nonce},
success: function(response) {
if(response.type == “success”) {
jQuery(“#like_counter”).html(response.like_count);
}
else {
alert(“Your like could not be added”);
}
}
});
});
});

 

Nguồn: https://wpmudev.com/blog/using-ajax-with-wordpress/