Last active
April 18, 2017 07:37
-
-
Save uprise10/3609d41ebda3830aa1a33629afd73532 to your computer and use it in GitHub Desktop.
WordPress Popular posts via AJAX
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
==== Javascript ==== | |
``` | |
$('.post-count').each( function() { | |
var postid = $(this).attr('id'); | |
$.ajax({ | |
url: uprs.ajax_url, | |
type: 'post', | |
dataType: 'html', | |
cache: false, | |
data: { | |
action: 'uprs_get_post_count', | |
postid: postid, | |
}, | |
success: function(data) { | |
$('#' + postid).html(data); | |
} | |
}); | |
}); | |
``` | |
===== PHP ===== | |
```add_action( 'wp_ajax_uprs_get_post_count', 'uprs_get_post_count' ); | |
add_action( 'wp_ajax_nopriv_uprs_get_post_count', 'uprs_get_post_count' ); | |
function uprs_get_post_count() { | |
$post_id = isset( $_POST['postid'] ) ? absint( $_POST['postid'] ) : 0; | |
$current_count = get_post_meta($post_id, 'views', true); | |
$new_count = (int)$current_count + 1; | |
update_post_meta($post_id, 'views', $new_count); | |
echo sprintf( __( '%s times read', 'tix' ), $current_count ); | |
die(); | |
}``` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment