• Hi, I’m developing a theme and I needed to create a meta field to count the hits for each post.

    Follows the code:

    function getPostViews($postID){
        $count_key = '_post_views_count';
        $count = get_post_meta($postID, $count_key, true);
        if($count==''){
            delete_post_meta($postID, $count_key);
            add_post_meta($postID, $count_key, '0');
            return "0 View";
        }
        return $count.' Views';
    }
    function setPostViews($postID) {
        $count_key = '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);
        }
    }

    Well, to test it I created 3 posts and when I hit the post #1, the counter of the post #1 and post #2 are increased simultaneously. The same issue occurs when I hit any post: the next post counter is increased too. Only the last post (most recent) works fine.

    The functions are called in the single.php file using the get_the_ID() function as the parameter.

Viewing 1 replies (of 1 total)
  • Thread Starter Anderson Veiga

    (@andersonv12)

    One more observation: I hit the post #1 and refresh the listing page and just the post #1 counter is increased, but when I refresh the page about 3 seconds later, the post #2 counter is increased too.

    And sorry for my English, I don’t speak fluently.

Viewing 1 replies (of 1 total)
  • The topic ‘Problem with update_post_meta function’ is closed to new replies.