WordPress.org

Ready to get started?Download WordPress

Forums

cookie in wordpress (1 post)

  1. lostheaven0809
    Member
    Posted 1 year ago #

    i'm creating a post view counter function using cookie. when a user has viewed specific post. a cookie will be created with name is the post ID. Note: get_the_ID() only use within the loop.
    i have made:

    function post_view_count(){
    global $newcount;
    $count_key='post_views_count'; a name of custom field of post
    $IDpost=get_the_ID();
    $count = get_post_meta($IDpost, $count_key, true); //i store post view counter in custom field of post.
    if (!isset($_COOKIE[$IDpost])) {
            $newcount=$count+1;
            update_post_meta($IDpost, $count_key, $newcount);
            setcookie($IDpost, 'viewed', time() + 1800);
        }
        else{
            $newcount=$count;
        }
        return $newcount;
    }

    Then include this function in the place you wish to show post view count.
    This function work well on localhost, a cookie haved been created (i showed cookie to check). But it did not run on server.
    Can u help me?

Topic Closed

This topic has been closed to new replies.

About this Topic