You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

获取特定作者所有文章总收藏数(基于favoriteposts.com插件)

如何在WordPress作者页展示所有文章累计收藏总数

我来帮你搞定这个需求!要在author.php页面给每位作者展示他们所有文章的累计收藏数,咱们可以通过自定义函数+模板调用的方式实现,具体步骤如下:

1. 编写计算总收藏数的自定义函数

把这段代码放到你主题的functions.php文件里就行。它会自动获取当前作者的所有已发布文章,累加每篇文章的收藏次数:

function get_author_total_favorites() {
    // 获取当前页面的作者ID
    $author_id = get_queried_object_id();
    
    if ( !$author_id ) return 0;
    
    // 查询该作者的所有已发布文章(如果有自定义文章类型,可在post_type里添加)
    $args = array(
        'author' => $author_id,
        'post_type' => 'post',
        'post_status' => 'publish',
        'posts_per_page' => -1, // 一次性获取所有文章
        'no_found_rows' => true, // 关闭分页计数,提升性能
        'update_post_term_cache' => false, // 禁用分类缓存,减少不必要的查询
        'update_post_meta_cache' => true, // 启用元数据缓存,加快获取速度
    );
    
    $author_posts = new WP_Query( $args );
    $total_favorites = 0;
    
    if ( $author_posts->have_posts() ) {
        while ( $author_posts->have_posts() ) {
            $author_posts->the_post();
            // 替换这里的元键为你实际存储收藏次数的键名!
            $post_favorites = get_post_meta( get_the_ID(), 'favorite_posts_count', true );
            // 确保数值有效,避免出错
            $total_favorites += is_numeric( $post_favorites ) ? intval( $post_favorites ) : 0;
        }
        wp_reset_postdata(); // 重置查询,避免影响后续内容
    }
    
    return $total_favorites;
}

⚠️ 重要提示:记得把代码里的'favorite_posts_count'替换成你网站实际存储收藏次数的元键。你可以通过查看数据库的wp_postmeta表,或者插件的设置/文档找到这个键名。

如果作者的文章数量特别多(比如上千篇),用上面的循环可能有点慢,推荐用下面的自定义SQL查询版本,效率更高:

function get_author_total_favorites() {
    $author_id = get_queried_object_id();
    if ( !$author_id ) return 0;
    
    global $wpdb;
    $total = $wpdb->get_var( $wpdb->prepare(
        "SELECT SUM(meta_value) FROM $wpdb->postmeta
         JOIN $wpdb->posts ON $wpdb->postmeta.post_id = $wpdb->posts.ID
         WHERE $wpdb->posts.post_author = %d
         AND $wpdb->posts.post_status = 'publish'
         AND $wpdb->posts.post_type = 'post'
         AND $wpdb->postmeta.meta_key = 'favorite_posts_count'",
        $author_id
    ) );
    
    return $total ? intval( $total ) : 0;
}

2. 在author.php中调用函数展示数值

找到你主题的author.php文件,在你想展示总收藏数的位置(比如作者简介下方、文章列表顶部)添加这段代码:

<div class="author-total-favorites">
    <p>您的所有文章累计收藏数:<strong><?php echo get_author_total_favorites(); ?></strong> 次</p>
</div>

如果想让这个区域更好看,可以加一点CSS样式,放到主题的style.css里:

.author-total-favorites {
    margin: 20px 0;
    padding: 15px;
    background-color: #f8f9fa;
    border-radius: 6px;
    font-size: 1.1em;
}

这样作者们就能在自己的个人资料页看到所有文章的累计收藏总数啦!

内容的提问来源于stack exchange,提问作者Chazlie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:36:24