Ad

Conditionally Calculate Sum Of Meta Values

- 1 answer

I want to calculate the sum of all meta values with the key _alg_wc_cog_order_profit only if order status is set to “completed”. I have created a shortcode for this but it does not return correct value and returns 0 instead. But if i replace the get_the_ID() with a specific post ID such as 56 or 11 it does return correct value.

Please guide me where i am making a mistake.

 add_shortcode('user_on_hold_cogs', 'get_user_orders_on_hold_totalb');
function get_user_orders_on_hold_totalb() {
    $total_amount = 0; // Initializing

    // Get current user
    if( $user = wp_get_current_user() ){

        // Get 'on-hold' customer ORDERS
        $on_hold_orders = wc_get_orders( array(
            'limit' => -1,
            //'customer_id' => $user->ID,
            'status' => 'completed',
        ) );



        foreach( $on_hold_orders as $order) {
            $stockk = (float) get_post_meta( get_the_ID() , '_alg_wc_cog_order_profit', true );
            //$total_amount += $order->get_total();
            $total_amount += $stockk ;
        }
    }
    return $total_amount;

}
Ad

Answer

On a quick check, you won't probably get the order id by using get_the_ID() here [assuming you are trying to access the order id.]

Try replacing get_the_ID() with $order->get_id()

Your code will become

$stockk = (float) get_post_meta( $order->get_id(), '_alg_wc_cog_order_profit', true );

Please let me know if the above code doesn't work.

Ad
source: stackoverflow.com
Ad