Sep
19
WordPress Count Post Views Without Plugin
Did you ever want to know how many times a particular post has been viewed? Well today is your lucky day. Just add the following snippets to your template files and watch the post views grow.
Usage
Add this to your functions.php
// Display or Count how many times a post has been viewed.
// id = the post id and action = display or count
function arixWp_PostViews( $id, $action ) {
$axCountMeta = 'ax_post_views'; // Your Custom field that stores the views
$axCount = get_post_meta($id, $axCountMeta, true);
if ( $axCount == '' ) {
if ( $action == 'count' ) {
$axCount = 0;
}
delete_post_meta( $id, $axCountMeta );
add_post_meta( $id, $axCountMeta, 0 );
if ( $action == 'display' ) {
echo "0 Views";
}
} else {
if ( $action == 'count' ) {
$axCount++;
update_post_meta( $id, $axCountMeta, $axCount );
} else {
echo $axCount . ' Views';
}
}
}
To count the views add this to your single.php template.
<?php echo arixWp_PostViews( get_the_ID(), 'count' ); ?>
To display the count outside the loop use this:
<?php echo arixWp_PostViews( get_the_ID(), 'display' ); ?>
If you want them to show in the loop use this instead.
<?php echo arixWp_PostViews( $post->ID, 'display' ); ?>
Tags: post views, WordPress


