WooCommerce get order quantity in thank you page a

2019-06-04 05:08发布

问题:

What I have done is I redirect the page after purchase but now I want to get the value of ordered quantity so that I can use it to my switch statement for some reason. How can I get the value of ordered quantity of the item?

function wc_custom_redirect_after_purchase() {
global $wp;

   if ( is_checkout() && ! empty( $wp->query_vars['order-received'] ) ) {
            //wp_redirect( 'http://grimmindustries.com.au/matchmaker/' );

    $quantity =  ; // ordered quantity that I need to use to switch statement to redirect

    switch($quantity) {
       case 1: 
          wp_redirect( 'http://www.facebook.com/' ); // exampe site
         break;
       case 2: 
          wp_redirect( 'http://www.youtube.com/' );  // exampe site
          break;
       default: 

          break;

}
    exit();
        }


}

回答1:

add_action('template_redirect', 'wc_custom_redirect_after_purchase');

function wc_custom_redirect_after_purchase() {
    global $wp;

    if (is_checkout() && !empty($wp->query_vars['order-received'])) {

        $order = new WC_Order($wp->query_vars['order-received']);

        $quantity = 0;
        if (count($order->get_items()) > 0) {
            foreach ($order->get_items() as $item) {

                if (!empty($item)) {
                    $quantity+= $item['qty'];
                }
            }
        }

        switch ($quantity) {
            case 1:
                wp_redirect('http://www.facebook.com/'); // exampe site
                break;
            case 2:
                wp_redirect('http://www.youtube.com/');  // exampe site
                break;
            default:

                break;
        }
        exit();
    }
}

Try this code snippet.