1

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?

Dharman
  • 30,962
  • 25
  • 85
  • 135
Snake
  • 466
  • 4
  • 16
  • Can you show the whole code function that works? `get_total(); ?>` – Vincenzo Di Gaetano Jan 29 '22 at 17:44
  • I literally put it in line 41 after the else (line 40) - https://woocommerce.github.io/code-reference/files/woocommerce-templates-checkout-thankyou.html – Snake Jan 29 '22 at 17:52
  • If you want to insert elements in that exact position you can only do it by overriding the [thankyou.php](https://woocommerce.github.io/code-reference/files/woocommerce-templates-checkout-thankyou.html) template (read the file header). You can find more information [here](https://woocommerce.com/document/template-structure/#how-to-edit-files). – Vincenzo Di Gaetano Jan 29 '22 at 18:04

1 Answers1

4

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.

Ruvee
  • 8,611
  • 4
  • 18
  • 44
  • Thanks for your intervention, it works correctly. However, I was wondering if there was an easier way to do this, perhaps avoiding overwriting the original template. – Snake Jan 29 '22 at 20:09
  • 2
    Since we're using the shortcode approach, it could **NOT** get any easier than this! FYI, we're **NOT** overwriting the plugin template. We're overriding it. There is a difference between the two. If you don't know about `overriding woocommerce templates`, then please take a moment and [read the documentation](https://woocommerce.com/document/template-structure/). – Ruvee Jan 29 '22 at 20:23