【问题标题】:Count occurrences of each value on specific meta value计算特定元值上每个值的出现次数
【发布时间】:2019-02-09 22:19:07
【问题描述】:

我有一个 wp_query 来检索具有特定 meta_key/meta_value 的所有帖子类型,但我无法更改它,因为此查询在同一页面的其他 5 个循环中使用。

$posts = new WP_Query(array(
    'posts_per_page'    => -1,
    'post_type'         => 'item',
    'post_status'       => 'publish',

    'meta_query'    => array(
        'relation'      => 'OR',
        array(
            'key'       => 'basicYear',
            'value'     => '1888',
            'compare'   => 'LIKE'
        ),
    )
));

我有这个循环只显示特定字段的信息;

while( $posts->have_posts() ){ 
        $posts->the_post();
        the_field('relBrand', get_field('basicBrandName'));  
    }

我需要计算 the_field('relBrand', get_field('basicBrandName')); 的出现次数

例如:品牌 A (1)、品牌 B (6)、品牌 D (2);

有没有人知道如何在不改变 wp_query 的情况下做到这一点?

【问题讨论】:

    标签: php sql wordpress


    【解决方案1】:

    您可以在顶部定义数组,然后只更新计数 $brandCounters = 数组();

    循环更改
    the_field('relBrand', get_field('basicBrandName')); 到

    $brand = get_field('relBrand', get_field('basicBrandName'));
    echo $brand;
    if(!empty($brandCounters[$brand])) {
        $brandCounters[$brand] = $brandCounters[$brand]++;
    }else{
        $brandCounters[$brand] = 1;
    }
    

    最好将此代码移动到函数中;

    【讨论】:

    • 完美的安德烈。非常感谢,只需将 ++ 更改为 +1 即可增加值。将我使用的值作为 foreach($brandCounters as $brand => $value){ echo $brand ." "。 $value ."
      "; }
    • 很高兴为您提供帮助))
    猜你喜欢
    • 2022-12-22
    • 1970-01-01
    • 2011-05-12
    • 1970-01-01
    • 1970-01-01
    • 2022-08-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多