要在WordPress中限制某個字段一天內的查看次數,你可以使用以下方法:
創建一個自定義的元數據字段來存儲查看次數。
使用鉤子(hook)來監聽頁面加載事件并檢查當前用戶的查看次數。
如果查看次數超過限制,則顯示一條消息告知用戶已超過查看次數限制。
以下是一個示例代碼,展示了如何實現這個功能:
//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 < $view_count_limit) {
update_post_meta($post_id, 'view_count', $view_count + 1);
} else {
// WodePress.com Display a message informing the user that the viewing limit has been exceeded
echo '<div class="notice notice-error is-dismissible">
<p>您已達到今天的查看次數限制。</p>
</div>';
}
}
}
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('Y-m-d', $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->ID, 'view_count', 0);
update_post_meta($post->ID, 'last_reset_time', $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');
}
}
請注意,這個示例代碼僅適用于已登錄的用戶,并且將查看次數限制應用于所有帖子。你可以根據需要修改這些設置。此外,你可能需要根據自己的主題和布局調整代碼以適應你的網站樣式。