WordPress如何向已登录用户展示已读文章并支持标记已读功能
WordPress已读文章功能实现方案
完全可以实现,以下是两种主流的落地方法:
方案1:现成插件快速实现
- 直接在WordPress后台插件市场搜索已读文章标记类插件即可,绝大多数相关插件默认支持已登录用户的阅读记录存储功能,还支持自定义是否在前端展示「标记为已读」按钮
- 插件默认会把用户阅读记录存在网站数据库的
wp_usermeta表中,不需要额外修改代码,基础配置完成后就可以直接在文章列表、单篇文章页展示对应的已读/未读状态
方案2:自定义代码实现(适合有定制需求的场景)
第一步:实现访问自动标记已读功能
将以下代码添加到主题的functions.php文件中,用户访问单篇文章时会自动将该文章标记为已读:
// 自动记录用户已读文章 function track_user_read_posts() { if (is_single() && is_user_logged_in()) { global $post; $user_id = get_current_user_id(); $read_posts = get_user_meta($user_id, 'user_read_posts', true); $read_posts = $read_posts ? $read_posts : array(); if (!in_array($post->ID, $read_posts)) { array_push($read_posts, $post->ID); update_user_meta($user_id, 'user_read_posts', $read_posts); } } } add_action('wp_head', 'track_user_read_posts');
第二步:添加「标记为已读」手动交互按钮
继续在functions.php中添加以下代码,即可在单篇文章内容末尾插入手动标记按钮:
// 前端插入标记为已读按钮 function add_mark_as_read_button($content) { if (is_single() && is_user_logged_in()) { global $post; $user_id = get_current_user_id(); $read_posts = get_user_meta($user_id, 'user_read_posts', true); if (!in_array($post->ID, (array)$read_posts)) { $button = '<form method="post" style="margin: 20px 0;"> <input type="hidden" name="mark_read_post_id" value="'.$post->ID.'"> <button type="submit" name="mark_as_read_submit" style="padding: 8px 15px; background: #2271b1; color: #fff; border: none; border-radius: 4px; cursor: pointer;">标记为已读</button> </form>'; $content .= $button; } } return $content; } add_filter('the_content', 'add_mark_as_read_button'); // 处理按钮提交请求 function handle_mark_as_read_submit() { if (isset($_POST['mark_as_read_submit']) && is_user_logged_in()) { $post_id = intval($_POST['mark_read_post_id']); $user_id = get_current_user_id(); $read_posts = get_user_meta($user_id, 'user_read_posts', true); $read_posts = $read_posts ? $read_posts : array(); if (!in_array($post_id, $read_posts)) { array_push($read_posts, $post_id); update_user_meta($user_id, 'user_read_posts', $read_posts); wp_redirect(get_permalink($post_id)); exit; } } } add_action('init', 'handle_mark_as_read_submit');
第三步:文章列表展示已读状态
在文章循环的合适位置添加以下代码,即可给已登录用户标注已读的文章:
if (is_user_logged_in()) { $user_id = get_current_user_id(); $read_posts = get_user_meta($user_id, 'user_read_posts', true); if (in_array(get_the_ID(), (array)$read_posts)) { echo '<span class="read-label" style="color: #2271b1; font-size: 12px; margin-left: 10px;">已读</span>'; } }
注意:如果站点使用了缓存插件,需要针对已登录用户关闭页面缓存,否则会出现已读状态展示异常的问题
内容的提问来源于stack exchange,提问作者Jake Lunniss
相关产品推荐
相关产品推荐

