Posts in this series
- Simple Post Views without a Plugin in WordPress
- Simple Post Views without Plugin in WordPress Part 2
- WordPress: Simple Post Views without a Plugin using Post Meta Part 3 - [ Shortcode support]
Here we will show you how you can add Simple Post Views without a Plugin in wordpress just by using post meta ,just follow these steps and your blog will be ready with post view counter
STEP 1 – Are you ready to add my simple Post Views without a Plugin in wordpress ?
Put this code in your theme’s functions.php file.Snippet below records post views using Post Meta
function my_get_post_views($post_id=0) { $count = 0; $post_id = !$post_id ? get_the_ID() : $post_id; $meta_count_key = 'my_views_count'; $count = get_post_meta($post_id, $meta_count_key, true); if ($count == '') { delete_post_meta($post_id, $meta_count_key); add_post_meta($post_id, $meta_count_key, '0'); return "0 View"; } return $count.' Views'; } function my_set_post_views($post_id = 0) { $post_id = !$post_id ? get_the_ID() : $post_id; if (!$post_id) { return; } $meta_count_key = 'my_views_count'; $count = get_post_meta($post_id, $meta_count_key, true); if ($count == '') { $count = 0; delete_post_meta($post_id, $meta_count_key); add_post_meta($post_id, $meta_count_key, '0'); } else { $count++; update_post_meta($post_id, $meta_count_key, $count); } } remove_action('wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0);
STEP 2
If you want to display post view counter in you page then you must put this code in your template file where you want post views to be displayed
<?php echo(my_get_post_views()); ?>
STEP 3
This step is very important as this snippet records post views to database so you must put this code in your single.php file.
<?php my_set_post_views(); ?>