隐藏运输选项Wooccommerce



所以我试图在Wooccommerce中基于产品标签隐藏某些发货方法。我面临的主要问题是我自己缺乏PHP知识,所以我在一些非常友好的人的帮助下,坦率地编写了以下代码:

add_filter( 'woocommerce_available_shipping_methods', 'hide_shipping_based_on_tag' ,    10, 1 );
function check_cart_for_share() {
// load the contents of the cart into an array.
global $woocommerce;
$cart = $woocommerce->cart->cart_contents;
$found = false;
// loop through the array looking for the tag you set. Switch to true if the tag is found.
foreach ($cart as $array_item) {
if (isset($array_item['product_tag']) && $array_item['product_tag'] == "CHOSEN_TAG") { // Replace "CHOSEN_TAG" with what ever tag you want
$found = true;
break;
}
}
return $found;
}
function hide_shipping_based_on_tag( $available_methods ) {
// use the function abve to check the cart for the tag.
if ( check_cart_for_share() ) {
// remove the rate you want
unset( $available_methods['flat_rate'] ); // Replace "flar_rate" with the shipping option that yu want to remove.
}
// return the available methods without the one you unset. 
return $available_methods;
}

我知道这段代码并不是通用的,因此变量会因情况而异,但也许有人可以告诉我代码中是否有问题。非常感谢

毫无疑问,您现在已经对此进行了排序,但您的代码对我来说是一个良好的开端。。。自从我整理了它之后,我在下面发表了它。你的问题是wooccommerce在cart数组中没有product_tag,所以你必须去获取它。

/* !Hide Shipping Options Woocommerce */
add_filter( 'woocommerce_available_shipping_methods', 'hide_shipping_based_on_tag' ,    10, 1 );
function check_cart_for_share() {
// load the contents of the cart into an array.
global $woocommerce;
$cart = $woocommerce->cart->cart_contents;
$found = false;
// loop through the array looking for the tag you set. Switch to true if the tag is found.
foreach ($cart as $array_item) {
    $term_list = wp_get_post_terms( $array_item['product_id'], 'product_tag', array( "fields" => "names" ) );
    if (in_array("Heavy",$term_list)) { // Replace "Heavy" with what ever tag you want
        $found = true;
        break;
    }
}
return $found;
}
function hide_shipping_based_on_tag( $available_methods ) {
// use the function above to check the cart for the tag.
if ( check_cart_for_share() ) {
    // remove the rate you want
    unset( $available_methods['flat_rate'] ); // Replace "flat_rate" with the shipping option that you want to remove.
}
// return the available methods without the one you unset.
return $available_methods;
}

您可以使用Wooccommerce的运输类来实现这一点。

以下是分步说明。

  • 创建运输类(wooccommerce->settings->shipping->shipping-classes)
  • 将此运输类与产品关联(您想隐藏其运输方法)
  • 使用此代码段。(复制并粘贴到function.php)

有关该片段的更多信息,请访问此处。

最新更新