如果订单商品属于特定产品类别,结帐重定向后的 Woocommerce

Woocommerce after checkout redirection if order items belongs to specific product categories

我需要做到这一点,当人们在我们的网上商店下单时,他们将被重定向到我的帐户,但前提是类别是 XXX、XXX、XXX

但不幸的是我似乎无法让它工作

我试过使用&& is_product_category('Category x','Category x','Category x')

// REDIRECT AFTER PLACE ORDER BUTTON!
add_action( 'woocommerce_thankyou', 'KSVS_redirect_custom');
function KSVS_redirect_custom( $order_id ){
    $order = new WC_Order( $order_id );

    $url = 'https://kanselvvilselv.dk/min-konto/';

    if ( $order->status != 'failed' ) {
        wp_redirect($url);
        exit;
    }
}

它在没有放入 && is_product_category('Category x','Category x','Category x') 的情况下工作,但是它在它不应该工作的类别上工作。

已更新,这应该遍历所有订购的产品,如果它匹配 1 个产品的类别,那么它将重定向到您的 URL:

add_action( 'woocommerce_thankyou', 'KSVS_redirectcustom');

function KSVS_redirectcustom( $order_id ){
    $order = wc_get_order( $order_id ); 
    $url = get_permalink( get_option('woocommerce_myaccount_page_id') );

    if ( $order->status != 'failed' ) {

        $product_cats = array('product-cat1', 'product-cat', 'product-cat3');

        foreach ($order->get_items() as $item) {

            if ( has_term( $product_cats, 'product_cat', $product->id) ) {
                $cat_check = true;
                break;
            }
        }

        if ( $cat_check ) {
            wp_redirect($url);
            exit;
        }
    }
}

注意:本人对woocommerce完全不熟悉,请放心回答。 似乎函数 is_product_category 有不同的用途,通过快速概览我得到了这个,试一试:

$redirectWhenCategoryIs = ['cat x', 'cat y', 'cat z'];

$categories = [];
foreach($order->get_items() as $item) {
    foreach(get_the_terms($item['product_id'], 'product_cat') as $term){
        $categories[] = $term->slug;
    }
}

if(count(array_intersect($redirectWhenCategoryIs, $categories))){
    wp_redirect($url);
}

以下代码使用专用 template_redirect 挂钩和 WordPress has_term() 条件函数 (与产品类别一起使用),将在结帐后将客户重定向到我的帐户部分,当他们的订单包含来自定义的产品类别的项目时:

add_action( 'template_redirect', 'order_received_redirection_to_my_account' );
function order_received_redirection_to_my_account() {
    // Only on "Order received" page
    if( is_wc_endpoint_url('order-received') ) {
        global $wp;

        // HERE below define your product categories in the array
        $categories = array('Tshirts', 'Hoodies', 'Glasses');

        $order = wc_get_order( absint($wp->query_vars['order-received']) ); // Get the Order Object
        $category_found = false;

        // Loop theough order items
        foreach( $order->get_items() as $item ){
            if( has_term( $categories, 'product_cat', $item->get_product_id() ) ) {
                $category_found = true;
                break;
            }
        }

        if( $category_found ) {
            // My account redirection url
            $my_account_redirect_url = get_permalink( get_option('woocommerce_myaccount_page_id') );
            wp_redirect( $my_account_redirect_url );
            exit(); // Always exit
        }
    }
}

代码进入您的活动子主题(或活动主题)的 function.php 文件。已测试并有效。