WooCommerce在感谢页面获取订单数量并重定向

时间:2016-06-27 14:46:51

标签: php wordpress woocommerce orders

我所做的是我在购买后重定向页面,但现在我想获得订购数量的值,以便我可以出于某种原因将它用于我的switch语句。如何获得物品的订购数量值?

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 个答案:

答案 0 :(得分: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();
    }
}

试试这个code snippet