1

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.

2

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.

3
  • Thanks @toscho it works like a charm :D, only there is one problem, when using with setPostViews it works okay, and value get into database, but when use for getPostViews, it show nothing, try to print_r(getPostViews()) still get nothing. Any idea? – nonsensecreativity Dec 10 '12 at 15:56
  • @nackle template_redirect action happens too early to print something out. I made an update with a second suggestion. – fuxia Dec 10 '12 at 16:02
  • thanks this is working great, btw you forgot to close the if statement, oh and I remove the if stamement since it looks like the getPostViews already handle the value to be 0 when there is no meta or post view. Thank you so much this really help me out – nonsensecreativity Dec 10 '12 at 16:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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