Count singular post views automatically

I’m trying to add some function to each loop called in the themes. What I’m doing is I add a function to count post view from here post views without plugin, to use the function I need to add this line <?php setPostViews(get_the_ID()); ?> to single.php, page.php, etc.

I want to know whether I can use some hook to automatically add the <?php setPostViews(get_the_ID()); ?> line without hard code it for each single.php, page.php files.

Related posts

Leave a Reply

1 comment

  1. You could hook into template_redirect and execute a helper function:

    add_action( 'template_redirect', 'wpse_75558_count' );
    
    function wpse_75558_count()
    {
        if ( is_singular() )
            setPostViews( get_the_ID() );
    }
    

    To display the post views, you have to use a later hook. I would recommend the_content:

    add_filter( 'the_content', 'wpse_75558_show_count' );
    
    function wpse_75558_show_count( $content )
    {
        $count = getPostViews( get_the_ID() );
    
        if ( ! is_numeric( $count ) )
            $count = ''; // prevent errors showing to visitors
        else
            $count = "<p class='view-count'>Views: $count</p>";
    
        return $content . $count;
    }
    

    Just an idea, I haven’t tested the code.