Snake93
Snake93

Reputation: 476

How to run a shortcode for WooCommerce view-order template

I'm trying to insert a shortcode in the woocommerce view-order.php template but it doesn't work. This is the reference template: https://woocommerce.github.io/code-reference/files/woocommerce-templates-myaccount-view-order.html

In the functions.php file I wrote the following code:

add_shortcode( 'order_view_id' , 'order_view_01' );
function order_view_01(){
$customer_id = get_current_user_id();
$order = new WC_Order( $order_id ); //I think this is the problem I don't know if that's right
return $order->get_id();
}

The shortcode shows the number 0, so I'm not getting the order id which in my case is 40001.

To structure the code I followed these references:

  1. How to create a shortcode for Woocommerce view-order template?

  2. Create Woocommerce shortcodes with order details

Maybe I should change the line that affects the $order part, but I'm not sure. I don't understand where I'm wrong, does anyone kindly have a suggestion?

Upvotes: 0

Views: 698

Answers (1)

Snake93
Snake93

Reputation: 476

Have found a solution.

After some research I came across this post: How can I get the order ID from the order Key in WooCommerce?

After that I tried to insert this $order_id = absint( get_query_var('view-order') ); Everything worked fine. Here is the solution for anyone in the same situation.

add_shortcode( 'order_view_id' , 'order_view_01' );
function order_view_01(){

// Get Order ID
$order_id = absint( get_query_var('view-order') );

// Then you can get the order object
$order = new WC_Order( $order_id );

// What you want to see, in my case the order ID
return $order->get_id();

}

Here you can find everything you are interested in showing via shortcode: https://www.businessbloomer.com/woocommerce-easily-get-order-info-total-items-etc-from-order-object/

Remember, I wrote the code in functions.php. This allows me to insert the [order_view_id] shortcode inside the woocommerce view-order.php template.

Upvotes: 0

Related Questions