Home > database >  WooCommerce how to get current order info on the thank you page using shortcode
WooCommerce how to get current order info on the thank you page using shortcode

Time:01-30

I'm trying to introduce a shortcode on the thankyou.php page to show the details of the order just placed by a customer.

If I write the code in php like this it works and shows the total: <?php echo $order->get_total(); ?>

Now I'm trying to get the same result through a shortcode, but I don't know some parameters and therefore can't get it to work.

<?php
add_shortcode( 'custom-woocommerce-total' , 'custom_total' );
function custom_total(){
    $customer_id = get_current_user_id();
    $order = new WC_Order($order_id); // I suppose that's not right.
    return $order->get_total();
} ?>

can anyone help me understand what I'm doing wrong?

CodePudding user response:

You would need to get the order id first by using global $wp variable. Try this:

add_shortcode('custom-woocommerce-total', 'custom_total');

function custom_total($attr)
{
    if (is_wc_endpoint_url('order-received')) 
    {
        global $wp;

        $order_id  = absint($wp->query_vars['order-received']);

        if ($order_id) 
        {
            $order = new WC_Order($order_id);

            if($order)
            {
              return $order->get_total();
            }

        }
    }
}

And in the thankyou page template use it like this:

echo do_shortcode('[custom-woocommerce-total]');

Don't forget to override the template.

  •  Tags:  
  • Related