WordPress中限制用户一天内的查看次数

要在WordPress中限制某个字段一天内的查看次数,你可以使用以下方法:

创建一个自定义的元数据字段来存储查看次数。

使用钩子(hook)来监听页面加载事件并检查当前用户的查看次数。

如果查看次数超过限制,则显示一条消息告知用户已超过查看次数限制。

以下是一个示例代码,展示了如何实现这个功能:

代码语言:javascript
复制
//Add custom metadata fields
function add_view_count_meta() {
    add_meta_box('view_count_meta', '查看次数限制', 'view_count_meta_callback', 'post', 'side', 'high');
}
add_action('add_meta_boxes', 'add_view_count_meta');

function view_count_meta_callback($post) {
view_count = get_post_meta(post->ID, 'view_count', true);
echo '<p>查看次数: ' . $view_count . '</p>';
}

//Listen for page loading events and check the number of views WodePress
function check_view_count_limit() {
//Check if the user is logged in, you can modify this condition as needed
if (is_user_logged_in()) {
$user_id = get_current_user_id();
$post_id = get_the_ID();
$view_count_limit = 10; //Set viewing limit
view_count = get_post_meta(post_id, 'view_count', true);

    //If the number of views has not reached the limit
    if ($view_count &lt; $view_count_limit) {
        update_post_meta($post_id, &#39;view_count&#39;, $view_count + 1);
    } else {
        // WodePress.com Display a message informing the user that the viewing limit has been exceeded
        echo &#39;&lt;div class=&#34;notice notice-error is-dismissible&#34;&gt;
            &lt;p&gt;您已达到今天的查看次数限制。&lt;/p&gt;
          &lt;/div&gt;&#39;;
    }
}

}
add_action('the_content', 'check_view_count_limit');

//Reset viewing times (optional, such as resetting in the early morning every day)
function reset_view_count() {
$current_time = current_time('timestamp');
today_start = strtotime(date(&#39;Y-m-d&#39;, current_time));
$args = array(
'post_type' => 'post',
'posts_per_page' => -1,
'post_status' => 'any',
'meta_query' => array(
array(
'key' => 'last_reset_time',
'value' => $today_start,
'compare' => '<',
'type' => 'NUMERIC'
)
)
);

$posts = get_posts($args);

foreach ($posts as $post) {
    update_post_meta($post-&gt;ID, &#39;view_count&#39;, 0);
    update_post_meta($post-&gt;ID, &#39;last_reset_time&#39;, $today_start);
}

}
// WodePress Add this hook to the scheduled tasks that are executed every morning
add_action('wp_scheduled_task', 'reset_view_count_daily_task');

function reset_view_count_daily_task() {
if (!wp_next_scheduled('reset_view_count')) {
wp_schedule_event(time(), 'daily', 'reset_view_count');
}
}

请注意,这个示例代码仅适用于已登录的用户,并且将查看次数限制应用于所有帖子。你可以根据需要修改这些设置。此外,你可能需要根据自己的主题和布局调整代码以适应你的网站样式。

原文

https://www.jianzhanpress.com/?p=7029