Search code examples
phpwordpresswoocommercehook-woocommerce

Woocommerce custom shortcode returns zero value


I have created a custom Thank you page in wordpress which has this paragraph:

Thank you so much for your order!

After paying off [cart_total] via XYZ website, please fill out this form and inform us about your payment.

And tried this custom shortcode:

// Total Price Shortcode 

function cart_wctotal(){

   global $woocommerce;
   $wctotal = $woocommerce->cart->get_cart_total();

   return "<span class='cart-total'> ".$wctotal."</span>";

}

add_shortcode( 'cart_total', 'cart_wctotal' );

But when I check out orders the output returns zero value for Total Price :

Thank you so much for your order!

After paying €0.00 via XYZ website, please fill out this form and inform us about your payment.


Solution

  • See comment from @xhynk why your code is not going to work.

    Get last order (and order total) by user id

    function cart_wctotal(){
        // Get user id
        $user_id = get_current_user_id();
    
        // Get last order by user id
        $last_order = wc_get_customer_last_order( $user_id );
    
        // Order total
        $wctotal = $last_order->get_total();
    
        return "<span class='cart-total'> " . $wctotal . "</span>";
    }
    add_shortcode( 'cart_total', 'cart_wctotal' );