Passing WooCommerce Order ID into a hook

2019-09-08 19:02发布

问题:

I have a recurring issue in my WooCommerce customizations: how to get the current order id inside a function.

Some hooks can pass it with $order_id, but in the context of a user's account page for a specific order, for example, the below doesn't work.

The problem is that $order_id is empty, of course. But how would I pass the ID of the order into this function?

add_action( 'woocommerce_order_items_table', 'xcsn_woocommerce_order_items_table');
function xcsn_woocommerce_order_items_table ( $order_id ) {

    $order = new WC_Order( $order_id );

    echo 'The order ID is: ' . $order->get_order_number();

    // or

    echo '<br>The order ID is: ' . $order->id;

}

I tried this, but it returns the user id number, not the order:

global $woocommerce;
$order = new WC_Order($post->ID);
echo 'The Order ID: ' . $order->get_order_number();

Any suggestions?

回答1:

This solves the particular issue above (though not the general question):

add_action( 'woocommerce_order_items_table', 'xcsn_woocommerce_order_items_table');
function xcsn_woocommerce_order_items_table ( $order ) {

    echo $order->id; //This is the order id, even in the user Accounts>Order page

}


回答2:

add_action( 'woocommerce_order_items_table', 'xcsn_woocommerce_order_items_table',10,2);
function xcsn_woocommerce_order_items_table ( $order_id ) {
    $order = new WC_Order( $order_id );
    echo 'The order ID is: ' . $order->get_order_number();
    // or
    echo '<br>
    The order ID is: ' . $order_id;

}

check this you need to add 10,2 on the action, that it returns the order id on after the successful order submission, without this the function will run before submit the order, so the order id maybe 0 or null