Full code hướng dẫn trong VIDEO
Rê vào vùng code rồi chọn Copy
add_filter('the_content', 'wpshare247_add_like_button', 1);
function wpshare247_add_like_button($content){
$post_id = get_the_ID();
?>
<script type="text/javascript">
jQuery(document).ready(function($) {
jQuery(".wpshare247-like").click(function(e) {
var wp_ajax_url = '<?php echo admin_url( 'admin-ajax.php' ); ?>';
jQuery.ajax({
url: wp_ajax_url,
type: 'POST',
data: {
action: "wpshare247_add_like_button",
post_id: <?php echo $post_id; ?>
},
dataType: 'json',
success: function(data, textStatus, jqXHR){
console.log(data); //return false;
var post_like = data.post_like;
jQuery(".wpshare247-like span").text(post_like);
},
error: function(jqXHR, textStatus, errorThrown){
}
});
return false;
});
});
</script>
<?php
$post_like = get_post_meta( $post_id, 'wpshare247_post_like', true );;
$btn_html = '<div id="wpshare247-buttons"><a class="wpshare247-like" href="#">Thích (<span>'.$post_like.'</span>)</a></div>';
$new_content = $content . $btn_html;
return $new_content;
}
//------------- Ajax wpshare247_action_load_more --------------------------
function wpshare247_add_like_button_display(){
header("Content-Type: application/json", true);
$arr_response = array();
//_REQUEST - 1 => Nhận dữ liệu từ Ajax Javascript
$post_id = $_REQUEST['post_id'];
//_ACTION - 2 => Xử lý tại đây
$post_like = get_post_meta( $post_id, 'wpshare247_post_like', true );
$post_like++;
update_post_meta( $post_id, 'wpshare247_post_like', $post_like );
//_RESPONSE - 3 => Trả kết quả về cho Ajax Javascript
$arr_response = array(
'post_like' => $post_like
);
wp_send_json($arr_response);
die();
}
add_action( 'wp_ajax_wpshare247_add_like_button', 'wpshare247_add_like_button_display' );
add_action('wp_ajax_nopriv_wpshare247_add_like_button', 'wpshare247_add_like_button_display');