Forum Topic: Pageview count even though there is a 301

Forum: .htaccess Forum : Redirecting • Posted by Jeroen • Post Date:

Jeff,

I noticed something I didn't expect. I have redirected a WordPress page to another one. The redirection works fine.

In the functions.php there is a php snippet that counts the pageviews and put them in the page's custom field. I use this code to order the posts on my homepage.

What I didn't expect was that the page that was redirected still gets view counts (is that good English?). I would say that even before getting to the functions.php the page is already redirected.

Any thoughts on this?

Cheers

Jeroen

6 Replies to “Pageview count even though there is a 301”

Jeff Starr
Posted by Jeff Starr

Hmm.. interesting.. what does the functions script look like?

Posted by Jeroen •

This is the tracking code.

//SET PAGEVIEWS
function wpb_set_post_views($postID) {
    $count_key = 'wpb_post_views_count';
    $count = get_post_meta($postID, $count_key, true);
    if($count==''){
        $count = 0;
        delete_post_meta($postID, $count_key);
        add_post_meta($postID, $count_key, '0');
    } else {
        $count++;
        update_post_meta($postID, $count_key, $count);
    }
}

//To keep the count accurate, lets get rid of prefetching
remove_action('wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0);

//ADD TRACKER TO HEADER
function wpb_track_post_views ($post_id) {
    //if ( !is_single() ) return;
	if ( is_user_logged_in() || is_page('Reset pageviews')) return;
    if ( empty ( $post_id) ) {
        global $post;
        $post_id = $post->ID;    
    }
    wpb_set_post_views($post_id);
}
add_action( 'wp_head', 'wpb_track_post_views');

then this on the homepage to order the posts

<?php 
$exclude_ids = array( 92, 99, 114, 414, 1251, 1353, 2726, 2741, 2752, 2758, 2834, 2848 );
$popularpost = new WP_Query( array( 'posts_per_page' => 8, 'meta_key' => 'wpb_post_views_count', 'orderby' => 'meta_value_num', 'order' => 'DESC', 'post__not_in' => $exclude_ids  ) );
while ( $popularpost->have_posts() ) : $popularpost->the_post();
?>
Jeff Starr
Posted by Jeff Starr

I use similar code for WP-Mix.com.. I think what is happening here is that the custom function is being executed for both the original request and the redirect URL.. which code are you using for the redirect? that may shed some further light on the issue..

Posted by Jeroen •

I use this for the redirect

Redirect 301 /dir/dir-2/slug http://example.com/dir/dir-2

Jeff Starr
Posted by Jeff Starr

I think that hooking into wp_head is the reason why both the original URL and the redirect URL are both being recorded for each request.. According to this page at the WP Codex, there are numerous hooks that execute before wp_head that you may want to try.. for example, init looks like a good candidate to start with..

Posted by Jeroen •

OK. Thanks Jeff. I'm going to look at it and let you know (after my holiday in Bali)