skip to Main Content

In WooCommerce, I am making a custom merchant plugin and I have added this hook:

add_action( 'woocommerce_order_details_after_order_table', 'track_me' );

Inside the track_me() function, I want to retrieve the order to do some things.

The function does what I want when I want, but I’m currently getting the order_id from the URL which seems janky.

I cannot figure out how to properly retrieve the $order object or the $order_id which would be enough.

It’s almost certainly something obvious as hours of searching the Internet has been fruitless. I just don’t know what the obvious something is…

UPDATE 1: Following the advice of @LoicTheAztec, I did the following:

do_action( 'woocommerce_order_details_after_order_table_items', $order );

class Order_MY extends WC_Order
{
    function __construct() 
    {
        add_action( 'woocommerce_order_details_after_order_table', array( $this, 'track_me' ) );
    }

    function track_me( $order ) 
    { 
        // My code here
    }
}

The first place the script fails is on the do_action line where PHP complains $order is an undefined variable.

The script also fails at extending WC_Order: Class ‘WC_Order’ not found

New question… is there something I need to do to make sure I have access to the woocommerce classes in my plugin?

2

Answers


  1. I am not an expert but maybe sth. like this could work:

    global $order_id;
    $order = wc_get_order($order_id);
    
    
    Login or Signup to reply.
  2. The WC_Order Object instance $order variable is included in the hook.
    You see that on order/order-details.php template file (line 76):

    do_action( 'woocommerce_order_details_after_order_table_items', $order );
    

    So you can use it in your hooked function this way:

    add_action( 'woocommerce_order_details_after_order_table', 'track_me' );
    
    function track_me( $order ) {
    
         // The Order ID
         $order_id = $order->get_id();
    
         // your code goes below
    }
    

    Now in a plugin, inside a class, you will replace:

    add_action( 'woocommerce_order_details_after_order_table', 'track_me' );
    

    by:

    add_action( 'woocommerce_order_details_after_order_table', array( $this, 'track_me' ) );
    

    Addition:

    As you can’t get the $order object from your plugin you should also try:

    add_action( 'woocommerce_order_details_after_order_table', 'track_me' );
    
    function track_me( $order ) {
    
         if ( ! is_a( $order, 'WC_Order' ) ) {
             global $order;
         }
    
         // The Order ID
         $order_id = $order->get_id();
    
         // your code goes below
    }
    

    I cant tell you anything more

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search