WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.

share|improve this question
up vote 2 down vote accepted

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
        $count = "<p class='view-count'>Views: $count</p>";

    return $content . $count;

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

share|improve this answer
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. – toscho 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 posting your answer, you agree to the privacy policy and terms of service.

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