首页 > 解决方案 > 如何在 wordpress 中跟踪登录用户最近阅读的文章

问题描述

我有一个 wordpress 网站,用户可以在其中注册并维护用户资料。

每个登录的用户都有 3 个选项卡,分别是推荐帖子、最近阅读的帖子和书签帖子。

现在,在最近阅读的帖子中,我正在努力寻找一种方法来跟踪某个用户阅读的帖子。

在不使用任何插件的情况下跟踪用户最近阅读的帖子的最佳方法是什么?任何小指南将不胜感激。

更新

提到的重复问题建议使用插件作为跟踪帖子的解决方案,但我不愿意使用插件。

标签: phpmysqlwordpress

解决方案


Cookie可以工作,但它不可靠并且绑定到浏览器,而不是帐户本身。您最好使用相对轻松地管理用户元字段update_user_meta()。如果你把它放在你的循环中的某个地方,或者你想要跟踪的帖子的模板上,它应该能让你开始。你甚至可以把它放在你的函数文件中,该文件在单个帖子特定的钩子上触发,只要最适合你的网站布局。

if( is_user_logged_in() ){
    $user_id = get_current_user_id();

    // Return "false" or an array of recent post ID's.
    if( $recently_read = get_user_meta( $user_id, 'recently_read', true ) ){
        // Insert the current post ID to the front of the array
        array_unshift( $recently_read, get_the_ID() );

        // Tracking limit if you want it, by slicing anything beyond the limit off.
        $tracking_limit  = 5;
        $new_recent_list = array_slice( $recently_read, 0, $tracking_limit );
    } else {
        $new_recent_list[] = get_the_ID();
    }

    // Save the new array to the user_meta field.
    update_user_meta( $user_id, 'recently_read', $new_recent_list );
}

请注意,正如所写的那样,这将允许重复的帖子,您可以if( !in_array( get_the_ID(), $recently_read) ){}很容易地在其中组合一些逻辑。

现在,您可以使用

get_user_meta( get_current_user_id(), 'recently_read', true )

例如:

$recent_ids = get_user_meta( get_current_user_id(), 'recently_read', true );

$recent_query = new WP_Query([
    'post__in' => $recent_ids;
]);

if ( $the_query->have_posts() ) {
    while ( $the_query->have_posts() ) {
        $the_query->the_post();
        echo get_the_title();
    }
    wp_reset_postdata();
}

推荐阅读