按产品类别隐藏运输方式,如果没有,则隐藏

问题描述 投票:0回答:1

如果购物车中有成品类别,而购物车中没有该类别,则我要组合一个函数来隐藏运输方法。这是我能够组合在一起的功能,但是不起作用。你能帮我吗?

function product_category_find_id_in_cart() {
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ){

    if ( has_term( 'hangers', 'product_cat', $cart_item['product_id'] ) ) {

    unset( $rates['free_shipping1'] );

    }
    else {
      unset( $rates['flat_rate:6'] );
   }

   return $rates;

}
}

我需要它还可以用于多种运输方式,而不仅仅是隐藏一种。谢谢!

由于@ 7uc1f3r,我有一个新代码,如果产品属于某个类别,则可以隐藏运输方式,但是我需要,如果产品不属于该类别,则其他运输方式也应隐藏。由于@LoicTheAztec,这将是新公式:

add_filter( 'woocommerce_package_rates', 'specific_products_shipping_methods', 10, 2 );
function specific_products_shipping_methods( $rates, $package ) {
    // HERE set the product category in the array (ID, slug or name)
    $terms = array( 'hangers' ); 
    $taxonomy = 'product_cat'; 

    // HERE set the shipping methods to be removed (like "fat_rate:5")
    $method_instances_ids = array('1');  

    $found = false;

    // Loop through cart items checking for defined product IDs
    foreach( $package['contents'] as $cart_item ) {
        if ( has_term( $terms, $taxonomy, $cart_item['product_id'] ) ){
            $found = true;
            break;
        }
    }

    if ( ! $found ) return $rates; // If not found we exit

    // Loop through your active shipping methods
    foreach( $rates as $rate_id => $rate ) {
        // Remove all other shipping methods other than your defined shipping method
        if ( in_array( $rate_id, $method_instances_ids ) ){
            unset( $rates[$rate_id] );
        }
    }    

    return $rates;
}
php wordpress woocommerce cart
1个回答
0
投票

我找到了!!

add_filter( 'woocommerce_package_rates', 'specific_products_shipping_methods', 10, 2 );
function specific_products_shipping_methods( $rates, $package ) {
    // HERE set the product category in the array (ID, slug or name)
    $terms = array( 'hangers' ); 
    $taxonomy = 'product_cat'; 

    // HERE set the shipping methods to be removed (like "fat_rate:5")
    $method_instances_ids = array('flat_rate:12','flat_rate:13','flat_rate:14');  

    $found = false;

    // Loop through cart items checking for defined product IDs
    foreach( $package['contents'] as $cart_item ) {
        if ( has_term( $terms, $taxonomy, $cart_item['product_id'] ) ){
            $found = true;
            break;
        }
    }

    if ( ! $found ) { unset( $rates['flat_rate:6'],$rates['flat_rate:7'],$rates['flat_rate:8'],$rates['flat_rate:9'],$rates['flat_rate:10'],$rates['flat_rate:11'] ); return $rates;} // If not found we exit
    else {
    // Loop through your active shipping methods
    foreach( $rates as $rate_id => $rate ) {
        // Remove all other shipping methods other than your defined shipping method
        if ( in_array( $rate_id, $method_instances_ids ) ){
            unset( $rates[$rate_id] );
        }
    }    

    return $rates;
}}
© www.soinside.com 2019 - 2024. All rights reserved.