求和后自定义元值

This should be really straightforward..

I have a custom post type: "shipment" with a custom field "shipment_cost"

I want to sum the total cost of all shipments.

I've managed to get it to output the correct amount with a single post:

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

But when I try to use all shipment CPTs in an array, I get a result of zero.

$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;

Is my shipments array wrong, or am I just going about this the wrong way in general?

Thanks!

Right now it seems that you are using $shipments as it was an array of post ids? You first need to retrieve all post ids:

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

Since the above would return post object you need to modify your loop:

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

A better and faster way might be to use a raw database query to get the sum for all meta values:

$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'");