How to save post visit or count post visit in wordpress

For get post visit or count post visit just copy and paste below code into your theme's functions.php file

add_action( 'wp_head', 'update_post_view' );
function update_post_view() {
    global $user_ID, $post;
    if( is_int( $post ) ) {
        $post = get_post( $post );
    }
    if( !wp_is_post_revision( $post ) ) {
        if( is_single() || is_page() ) {
            $id = intval( $post->ID );
           
            if ( !$post_views = get_post_meta( $post->ID, '_visitor_count', true ) ) {
                $post_views = 0;
            }
            $should_count = true;
              $bots = array
                (
                      'Google Bot' => 'googlebot'
                    , 'Google Bot' => 'google'
                    , 'MSN' => 'msnbot'
                    , 'Alex' => 'ia_archiver'
                    , 'Lycos' => 'lycos'
                    , 'Ask Jeeves' => 'jeeves'
                    , 'Altavista' => 'scooter'
                    , 'AllTheWeb' => 'fast-webcrawler'
                    , 'Inktomi' => 'slurp@inktomi'
                    , 'Turnitin.com' => 'turnitinbot'
                    , 'Technorati' => 'technorati'
                    , 'Yahoo' => 'yahoo'
                    , 'Findexa' => 'findexa'
                    , 'NextLinks' => 'findlinks'
                    , 'Gais' => 'gaisbo'
                    , 'WiseNut' => 'zyborg'
                    , 'WhoisSource' => 'surveybot'
                    , 'Bloglines' => 'bloglines'
                    , 'BlogSearch' => 'blogsearch'
                    , 'PubSub' => 'pubsub'
                    , 'Syndic8' => 'syndic8'
                    , 'RadioUserland' => 'userland'
                    , 'Gigabot' => 'gigabot'
                    , 'Become.com' => 'become.com'
                    , 'Baidu' => 'baiduspider'
                    , 'so.com' => '360spider'
                    , 'Sogou' => 'spider'
                    , 'soso.com' => 'sosospider'
                    , 'Yandex' => 'yandex'
                );
                $useragent = $_SERVER['HTTP_USER_AGENT'];
                foreach ( $bots as $name => $lookfor ) {
                    if ( stristr( $useragent, $lookfor ) !== false ) {
                        $should_count = false;
                        break;
                    }
                }
           
            if( $should_count ) {
                update_post_meta( $id, '_visitor_count', ( $post_views + 1 ) );
            }
        }
    }
}

Comments

Popular posts from this blog

How to add image option in nav menu in wordpress

How to use multiple plupload instance in a single form or single page

How to execute wp_schedule_event event on custom time interval in wordpress