doubipiao1611 2018-07-19 08:40
浏览 76

如何计算页面的meta_key?

Is it possible to count the amount of the same meta_keys for the same post_id.

I have a page with the post_id 44 and every time a user submits something on this page a new database rule is added with the meta_key "post_rating_0".

There are over 30 rules now for this page and I want to count them. For other pages the same thing.

Is this possible?

Code so far:

global $post;
$query_args = array(
            'post_type' => 'page',
            'post_status' => 'publish',
            'posts_per_page' => -1,
            'meta_key' => 'post_rating_0'
            // 'fields' => 'SUM(amount_to_paid)',
        );

$sum = 0;
$query = new WP_Query($query_args);
if ( $query->have_posts() ) {
    while( $query->have_posts() ) {
        $query->the_post();
        // do the processing for each post
        $sum = $sum + intval(get_post_meta(get_the_id(),'post_rating_0', true ));
    }
}
echo $sum ;

This is what I got so far... But what this does is echo the value of "2" what is very logic. It searches for posts with the meta_key "post_rating_0", counts them and that are 2 posts.

What I'm trying to do is count the amount of meta_keys "post_rating_0" are in one page.

  • 写回答

2条回答 默认 最新

  • douyi4544 2018-07-19 09:01
    关注

    This modified code will give you an array with all post_id and the corresponding amount of your specific meta:

    $meta_arr = array();
    $query = new WP_Query($query_args);
    if ( $query->have_posts() ) {
        while( $query->have_posts() ) {
            $query->the_post();
            $post_id = get_the_id();
            $meta_arr[$post_id] = intval(get_post_meta($post_id, 'post_rating_0', false));
        }
    }
    
    print_r($meta_arr);
    
    评论

报告相同问题?

悬赏问题

  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探