检查用户今天是否已经访问过此帖子

时间:2016-05-28 作者:Boris Kozarac

我有一段代码来衡量一篇文章的受欢迎程度。如果用户在过去24小时内没有访问过此帖子,我该如何检查?我是否需要为用户和他们访问的每个帖子设置cookie?我

$count = get_post_meta($post_id, \'popular_posts\', true);
    if(user-didnt-visited-this-page-in-last-24-hours) : 
       $count++;
       update_post_meta($post_id, $count_key, $count);
    endif; 

1 个回复
最合适的回答,由SO网友:Max Yudin 整理而成

笔记此代码未经测试!

<?php
function my_visitor_cookie($post_id) {

    if ( empty($post_id) ) {
        global $post;
        $post_id = $post->ID;    
    }

    // get post meta
    $count = get_post_meta($post_id, \'unique_post_visits\', true);

    // if there was no meta value
    if( empty($count) ) {
        $count = 0;
    }

    // check if cookie was already set (cookie name for the current post)
    if( !isset($_COOKIE[\'my_visitor_\' . $post_id]) ) {
        // set visitor cookie if it is not set already
        setcookie(
            \'my_visitor_\' . $post_id, // cookie name for the current post
            $post_id, // any value, shot in the dark
            DAY_IN_SECONDS // WordPress time constant
        );
        // increase count
        $count++;
        // update count
        update_post_meta($post_id, \'unique_post_visits\', $count);
    }
}

// add_action(\'wp_head\', \'my_visitor_cookie\');
add_action(\'init\', \'my_visitor_cookie\'); // updated according to the comments