Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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
add comment

1 Answer

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
    else
        $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? –  nackle 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 –  nackle Dec 10 '12 at 16:13
add comment

Your Answer

 
discard

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.