求和后自定义元值

时间:2018-01-27 09:35:05

标签: php wordpress

这应该非常简单..

我有自定义帖子类型:"货件"使用自定义字段" shipment_cost"

我想总计所有货件的总成本。

我设法通过一个帖子让它输出正确的金额:

$totalcost = 0;
$post_ids = [2583];
foreach( $post_ids as $post_id )
{ 
    $totalcost += (int) get_post_meta( $post_id, 'shipment_cost', true );
}
echo $totalcost;

但是当我尝试在阵列中使用所有出货CPT时,我得到零结果。

$shipments = array(
'post_type'     => 'shipment'
);
$totalcost = 0;
$post_ids = $shipments;
foreach( $post_ids as $post_id )
{ 
    $totalcost += (int) get_post_meta( $post_id, 'shipment_cost', true );
}
echo $totalcost;

我的货物阵列是错误的,还是我只是错误地采用这种方式?

谢谢!

2 个答案:

答案 0 :(得分:1)

现在看来你正在使用$shipments,因为它是一组post id?您首先需要检索所有帖子ID:

$shipments = get_posts(array(
  'post_type' => 'shipment',
  'post_status' => 'publish'
));

由于上面会返回post对象,你需要修改你的循环:

foreach ($shipments as $post) {
  $totalcost += (int) get_post_meta($post->ID, 'shipment_cost', true);
}

更好更快的方法可能是使用原始数据库查询来获取所有元值的总和:

$totalcost = $wpdb->get_col("SELECT SUM(pm.meta_value) FROM {$wpdb->postmeta} pm
                             INNER JOIN {$wpdb->posts} p ON p.ID = pm.post_id
                             WHERE pm.meta_key = 'shipment_cost' 
                             AND p.post_status = 'publish' 
                             AND p.post_type = 'shipment'");

答案 1 :(得分:0)

这才救了我的命!!一直在寻找针对Pods Custom Post Type的总输入的解决方案,该Pod Custom Post Type具有一个Custom字段,用户可以在其中输入数字。然后,我将代码包装成简码以显示在前端

button_Click()

谢谢!