Saeng Sisou
Saeng Sisou

Reputation: 15

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

I want to create a shortcode for view-order.php template, which is located in my child theme /woocommerce/myaccount/view-order.php or can be accessed via url /my-account/view-order/{id}/ I've read this article How to create a shortcode for custom page template? and adjusted the code as below:

function view_order_shortcode() {
   ob_start();
   get_template_part('view-order');
   return ob_get_clean();   
} 
add_shortcode( 'view_order_shortcode', 'view_order_shortcode' );

Then I insert <?php echo do_shortcode("[view_order_shortcode]"); ?> into a template where I want it to display but it's not working.

I read this article as well Woocommerce - How to show Order details (my-account) on a separate page but this one talks about my-orders.php The code below works fine.

function woocommerce_orders() {
    $user_id = get_current_user_id();
    if ($user_id == 0) {
         return do_shortcode('[woocommerce_my_account]'); 
    }else{
        ob_start();
        wc_get_template( 'myaccount/my-orders.php', array(
            'current_user'  => get_user_by( 'id', $user_id),
            'order_count'   => $order_count
         ) );
        return ob_get_clean();
    }

}
add_shortcode('woocommerce_orders', 'woocommerce_orders');

However, I've adjusted it to bellow but it's not working. Any suggestion?

function woocommerce_orders() {
    $user_id = get_current_user_id();
    if ($user_id == 0) {
         return do_shortcode('[woocommerce_my_account]'); 
    }else{
        ob_start();
        wc_get_template( 'myaccount/view-order.php', array(
            'current_user'  => get_user_by( 'id', $user_id),
         ) );
        return ob_get_clean();
    }

}
add_shortcode('woocommerce_orders', 'woocommerce_orders');

Upvotes: 1

Views: 1444

Answers (1)

Elvis Chan
Elvis Chan

Reputation: 36

view-order.php template requires two parameters to get it to work.

  1. order
  2. order_id

In your example, this should work.

function woocommerce_view_order($params) {
    $order_id = $params['order_id'];  // get order id from shortcode params
    $user_id = get_current_user_id();
    if ($user_id == 0) {
         return do_shortcode('[woocommerce_my_account]'); 
    }else{
        ob_start();
        wc_get_template( 'myaccount/view-order.php', array(
            'order' => wc_get_order($order_id), // add this line
            'order_id' => $order_id //add this line
         ) );
        return ob_get_clean();
    }

}
add_shortcode('woocommerce_view_order', 'woocommerce_view_order');

Then, apply the shortcode with an order id:
Example: [woocommerce_view_order order_id=103]

Upvotes: 2

Related Questions