Skip to content

Instantly share code, notes, and snippets.

@DavidPeralvarez DavidPeralvarez/ajax-1.js Secret
Created Feb 5, 2020

Embed
What would you like to do?
Plugin Me Gusta
(function($) {
var likeButton = $( "#like-button" );
likeButton.on( "click", function(e) {
e.preventDefault();
var likes = likeButton.find('span').text(),
postId = likeButton.data('post');
$.ajax({
type: 'post',
dataType: 'json',
url: a1_parameters.ajax_url,
data: {
action: 'a1_like_post',
_ajax_nonce: a1_parameters.nonce,
likes: likes,
postId: postId
},
beforeSend: function(){
console.log( 'Cargando...' );
},
success: function( response ){
if( 'success' == response.type ){
likeButton.find('span').text( response.likes );
} else {
console.log( 'Ha fallado.' );
}
}
});
});
}) ( jQuery );
<?php
/*
Plugin Name: Ajax 1
Description: Like en posts
*/
// Add like and counter link
add_filter( 'the_content', 'a1_add_like_link' );
function a1_add_like_link( $content ){
if( !is_singular( 'post' ) ) return $content;
$post_id = get_the_ID();
$current_likes = get_post_meta( $post_id, 'a1_post_likes', true );
$current_likes = ($current_likes == '') ? 0 : $current_likes;
return $content . '<p><a href="#" id="like-button" data-post="' . $post_id . '"><span>' . $current_likes . '</span> Me gusta</a></p>';
}
// Enqueue scripts
add_action( 'wp_enqueue_scripts', 'a1_enqueue_scripts' );
function a1_enqueue_scripts(){
if( is_singular( 'post' ) ):
wp_enqueue_script(
'ajax-1',
plugins_url( '/ajax-1.js', __FILE__ ),
['jquery'],
'1.0',
true
);
wp_localize_script(
'ajax-1',
'a1_parameters',
[
'ajax_url' => admin_url( 'admin-ajax.php' ),
'nonce' => wp_create_nonce( 'a1_nonce' )
]
);
endif;
}
// Like a post
add_action( 'wp_ajax_a1_like_post', 'a1_like_post' );
add_action( 'wp_ajax_nopriv_a1_like_post', 'a1_like_post' );
function a1_like_post(){
check_ajax_referer( 'a1_nonce' );
$likes = intval( $_POST['likes'] ) + 1;
$post_id = intval( $_POST['postId'] );
$success = update_post_meta( $post_id, 'a1_post_likes', $likes );
if( $success == true ):
$response['likes'] = $likes;
$response['type'] = 'success';
else:
$response['type'] = 'failure';
endif;
$response = json_encode( $response );
echo $response;
wp_die();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.