3

I am very new to WordPress plugin development.

I have been searching this for a quite a while now but I am currently creating a plugin and I need my plugin to start logging the amount of views a post has had. I already know what I want this part of to do however I am having trouble find out how to a PHP function for when a post is viewed by a visitor to my WordPress site.

Could someone please show me what the WordPress hook/event is to run a function on post view/load? I want to do this without the use of template as well.

2 Answers 2

6

I assume you are looking for a conditional to check if you are on a post page.

You can do so by using is_single():

if (is_single()) {
    // Update your post views here
}

If you insist on using filters or hooks, you can use the_content filter:

add_filter( 'the_content', 'update_post_views' );
function update_post_views($content){
    if (is_single()) {
        $id = get_the_ID();
        // Now update your post's views
    }
    return $content;
}
1
  • I shall when they let me accept it in a few minutes
    – Dev Daniel
    Commented Jun 12, 2017 at 13:00
1

First, let's try to add post views to the dashboard -> posts. First, we add a new column there:

add_filter('manage_posts_columns', function($columns) {
    return array_merge($columns, ['post_views' => 'Views']);
});

Then, we are going to show the number of views. We assume that (Like many other guides on the web), there is a meta key post_views holding the number of post views.

add_action('manage_posts_custom_column', function($column) {
    if ($column === 'post_views') {
        $count = get_post_meta(get_the_ID(), 'post_views_count', true);
        echo empty($count) ? 'no views :(' : "$count view :)";
    }
});

You should be able to see this new column on the posts admin table.

post views wordpress

Finally, we have the real code to update the post_views meta every time a post is visited.

function jj_count_post_views($content)
{
    if (is_single() && !is_preview()) {
        $postId = get_the_ID();

        update_post_meta(
            $postId,
            'post_views_count',
            (int) get_post_meta($postId, 'post_views_count', true) + 1
        );

        remove_filter('the_content', 'jj_count_post_views');
    }

    return $content;
}

add_filter('the_content', 'jj_count_post_views');

Please notice that the remove_filter is necessary, because some plugins use the_content filter to do more stuff to the content (like SEO plugins), so the_content will be called multiple times. Thanks to this answer.

Also, remove && !is_preview() if you want to count all the views, even the preview ones.

P.S. Add all those codes inside theme functions.php and it works.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.