This is a part 2 of our article on how to add Simple Post Views without Plugin in WordPress,In this part we will add more optional features to our code

In previous part we shown you how to create a simple post view counter without a Plugin and just using Post meta.Now in this second part we will extend our existing function and we will add some more features to it .So we are going to add some more parameters to my_get_post_views  function.

What I am going to do is i will add few more parameters so we will have more control to our post views counter function.

function my_get_post_views($post_id=0, $update_view = false, $hide_on_zero = false, $append_singular = "View", $append_plural = "Views", $enclosed_html = "%s")
{
$count = 0;
$post_id = !$post_id ? get_the_ID() : $post_id;
if ($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');
}

$count = intval($count);
}

if ($count) {
if ($count > 1) {
$views = sprintf($enclosed_html, $count . " " . $append_plural);
}
else {
$views = sprintf($enclosed_html, $count . " " . $append_singular);
}

$views = sprintf($enclosed_html, $count . " " . ($count > 1 ? $append_plural : $append_singular));
}
else {
if ($hide_on_zero) {
$views = "";
}
else {
$views = sprintf($enclosed_html, $count . " " . $append_singular);
}
}

if ($update_view) {
my_set_post_views($post_id);
}

return $views;
}

as you can see i have added 5 more parameters to our function my_get_post_views ,Let me give details about each parameters i added.

$update_view  – if true this function will also update the view counter.No need to call my_set_post_views function to update counter
$hide_on_zero  – If you do not want 0 views to be displayed set it to true.
$append_singular  – Text to append if number of view is singular ( less then 2).
$append_plural  – Text to append if number of view is plural ( greater then 1 ).
$enclosed_html  – you can also put a custom html to wrap views and %s will be replaced with total post views Ex: <h1>%s</h1>

 

You may also like: