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

如何在CPT归档页统计ACF字段complete的已完成文章数?

获取ACF True/False字段的已完成文章数(自定义文章类型归档页)

下面提供几种可行的方案,你可以根据自己的场景选择:

方案一:循环当前归档文章统计

利用归档页的主查询文章列表,逐个检查complete字段值并累加计数:

// 初始化已完成计数
$completed_count = 0;

// 遍历当前归档的文章
if ( have_posts() ) {
    while ( have_posts() ) {
        the_post();
        // 获取当前文章的complete字段值
        $is_completed = get_field( 'complete' );
        // 字段为true时计数+1
        if ( $is_completed ) {
            $completed_count++;
        }
    }
    // 重置文章数据,避免影响后续内容
    wp_reset_postdata();
}

// 你已获取的总文章数
$total_count = $GLOBALS['wp_query']->found_posts;

// 输出结果
echo "<p>{$completed_count}/{$total_count}已完成</p>";

适合归档文章数量不多的场景,无需额外查询,直接复用主查询结果。

方案二:用WP_Query单独查询计数

如果不想遍历主查询文章,可以单独构建元查询,直接获取符合条件的文章数量,性能更优:

// 总文章数
$total_count = $GLOBALS['wp_query']->found_posts;

// 替换为你的自定义文章类型slug
$cpt_slug = 'your_cpt_slug';

// 构建查询参数
$completed_query = new WP_Query( array(
    'post_type'      => $cpt_slug,
    'posts_per_page' => -1,
    'meta_query'     => array(
        array(
            'key'     => 'complete',
            'value'   => '1', // ACF的True/False字段存储值为1(真)或0(假)
            'compare' => '=',
        )
    ),
    'fields'         => 'ids', // 只返回文章ID,减少资源占用
) );

$completed_count = $completed_query->found_posts;

// 输出结果
echo "<p>{$completed_count}/{$total_count}已完成</p>";

// 重置查询
wp_reset_postdata();

注意将your_cpt_slug替换为你的自定义文章类型的实际slug。

方案三:直接用SQL查询(大数据量最优)

如果你的自定义文章类型文章数量极大,直接执行SQL查询是性能最好的方式:

global $wpdb;

// 替换为你的自定义文章类型slug
$cpt_slug = 'your_cpt_slug';

// 总文章数
$total_count = $GLOBALS['wp_query']->found_posts;

// 查询已完成文章数量
$completed_count = $wpdb->get_var( $wpdb->prepare(
    "SELECT COUNT(p.ID) FROM {$wpdb->posts} p
    JOIN {$wpdb->postmeta} pm ON p.ID = pm.post_id
    WHERE p.post_type = %s
    AND p.post_status = 'publish'
    AND pm.meta_key = 'complete'
    AND pm.meta_value = '1'",
    $cpt_slug
) );

// 输出结果
echo "<p>{$completed_count}/{$total_count}已完成</p>";

通过$wpdb->prepare确保SQL语句的安全性,避免注入风险。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 23:03:23