如何检查(在每个会话中)是否查看过帖子或媒体资源

时间:2019-06-18 10:29:43

标签: javascript php wordpress cookies

我使用的是RealHomes Wordpress主题,我想记住每个属性的点击次数,但仅限一次。

例如,我去一个网站查看一些属性,然后单击其中一些,然后稍后刷新页面时,它会说这些属性已被看到,也许只是一个文字,内容为“ ”。

稍后或明天,当我转到同一页面时,所有这些属性都不应显示“ Seen”消息,我想重置点击/视图。

我的functions.php文件中有这两个函数,可以在要显示计数器的位置调用getPostViews,并在single.php属性文件的开头调用setPostViews。

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);
    }

    add_action('end_session_action','end_session'); 
}

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;
}

我愿意在首页上的每个媒体资源旁边显示点击次数。

Image: property has been seen

Image: property hasn't been seen

我的问题是,如何在每个新会话中重置此元值?

我还发现此代码显示用户上次访问网站的时间,每次都会重置时钟。

function viewed_cookie($postID) {

    // Time of user's visit
    date_default_timezone_set("Europe/Ljubljana");
    $visit_time = date('d.m.Y. G:i');

    // Check if cookie is already set
    if(isset($_COOKIE['visited_cookie'])) {
        // Do this if cookie is set 
        function postViewed() {

            // Use information stored in the cookie 
            $lastvisit = $_COOKIE['visited_cookie'];
            $string .= $lastvisit; 

            // Delete the old cookie so that we can set it again with updated info
            unset($_COOKIE['visited_cookie']); 

            return $string;
        }   
    } else { 
        // Do this if the cookie doesn't exist
        function postViewed() { 
            $string .= 'New here? Check out these resources...' ;
            return $string;
        }   
    }

    add_shortcode('viewed', 'postViewed');

    // Set or Reset the cookie
    setcookie('visited_cookie',  $visit_time);

}
add_action('init', 'viewed_cookie'); 

如何像上一个示例一样合并set / get函数并使用cookie?

0 个答案:

没有答案