Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Add a Like button to category/tag/taxonomy pages
jQuery( document ).on( 'click', '.pt-tax-like-it', function() {
var $this = jQuery(this),
id = jQuery(this).find('.like-button').attr('data-id'),
nonce = jQuery(this).find('.like-button').attr("data-nonce");
jQuery.ajax({
url : taxlikeit.ajax_url,
type : 'post',
data : {
action : 'pt_tax_like_it',
id : id,
nonce : nonce
},
success : function( response ) {
jQuery( '#like-count-'+id ).html( response );
}
});
return false;
})
<?php
add_action( 'wp_ajax_nopriv_pt_tax_like_it', 'pt_tax_like_it');
add_action( 'wp_ajax_pt_tax_like_it', 'pt_tax_like_it');
function pt_tax_like_it() {
if ( ! wp_verify_nonce( $_REQUEST['nonce'], 'pt_tax_like_it_nonce' ) || ! isset( $_REQUEST['nonce'] ) || ! isset( $_REQUEST['id'] ) ) {
exit( "No naughty business please" );
}
$id = $_REQUEST['id'];
if ( get_term_meta( $id, '_pt_tax_likes', true ) ) {
$likes = get_term_meta( $id, '_pt_tax_likes', true );
} else {
$likes = 0;
add_term_meta( $id, '_pt_tax_likes', $likes, true );
}
$new_likes = $likes + 1;
update_term_meta( $id, '_pt_tax_likes', $new_likes );
if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
echo $new_likes;
die();
}
}
add_action( 'wp_enqueue_scripts', 'pt_tax_like_it_scripts', 100 );
function pt_tax_like_it_scripts() {
if ( is_tax() || is_category() || is_tag() ) {
if ( !wp_script_is( 'jquery', 'enqueued' ) ) {
wp_enqueue_script( 'jquery' ); // Comment this line if you theme has already loaded jQuery
}
wp_enqueue_script( 'tax-like-it', trailingslashit( plugin_dir_url( __FILE__ ) ).'js/tax-like-it.js', array('jquery'), '1.0', true );
wp_localize_script( 'tax-like-it', 'taxlikeit', array(
'ajax_url' => admin_url( 'admin-ajax.php' )
));
}
}
function pt_tax_like() {
global $wp_query;
$like_text = '';
if ( !is_tax() && !is_category() && !is_tag() ) return;
$tax = $wp_query->get_queried_object();
$id = $tax->term_id;
$nonce = wp_create_nonce( 'pt_tax_like_it_nonce' );
$likes = get_term_meta( $id, '_pt_tax_likes', true ) ? get_term_meta( $id, '_pt_tax_likes', true ) : 0;
$like_text = '
<a class="pt-tax-like-it">
<button class="like-button" data-id="' . $id . '" data-nonce="' . $nonce . '">' . '
<span id="like-count-'.$id.'" class="like-count">' . $likes . '</span>' . '
</button>
</a>';
echo $like_text;
}
<?php pt_tax_like();?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment