WooCommerce - get_order() is not working

2019-05-03 08:39发布

问题:

I'm trying to create a function that will retrieve an order by its ID. For some reason I can't get the WooCommerce global function get_order to work. I'm passing a valid order id to the function and trying to print it out to verify that it's working. The function has been placed in my functions.php file.

function getWC_order_details($id){
    global $woocommerce;

    $order = get_order( $id );

    print "<pre>";
    print_r($order);
    print "</pre>";
}

I have tested echoing other data out of the function without a problem.

回答1:

First of all make function like this :

function getWC_order_details($order_id) { 
    $order = new WC_Order( $order_id );
    var_dump($order);
}

After that, use it with some woo_commerce action or filter.

function use_after_cart_table(){
    getWC_order_details(40);
}
add_action( 'woocommerce_after_cart_table', 'use_after_cart_table' );

So after adding any product to the cart, you will see after cart table that there is one array containing all the details.

NOTE : You can use any other action or filter and you can find them here.

EDITED:

function getWC_order_details($order_id) { 
    $order = new WC_Order( $order_id );
    //var_dump($order);
    $order_shipping_total = $order->get_shipping();
    $order_shipping_method = $order->get_shipping_methods();
    var_dump($order_shipping_total);//Use it for debugging purpose or to see details in that array
    var_dump($order_shipping_method);//Use it for debugging purpose or to see details in that array

    $_order =   $order->get_items(); //to get info about product
    foreach($_order as $order_product_detail){
        //var_dump($order_product_detail);
        echo "<b>Product ID:</b> ".$order_product_detail['product_id']."<br>";
        echo "<b>Product Name:</b> ".$order_product_detail['name']."<br><br>";
    }
    //var_dump($_order);
}


回答2:

try this.It might be useful to you.

function getWC_order_details($id)
{
 $array = WC_API_Orders::get_order( $id, $fields );
 print "<pre>";
 print_r($order);
 print "</pre>";
}

Source: File name: woocommerce/includes/api/class-wc-api-orders.php