wordpress - 隐藏运输选项 Woocommerce

标签 wordpress woocommerce

所以我试图根据产品标签在 Woocommerce 中隐藏某些运送方法。我面临的主要问题是我自己缺乏 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;

}

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

最佳答案

毫无疑问,您现在已经对它进行了排序,但是您的代码对我来说是一个良好的开端……并且由于我对它进行了排序,所以我已经在下面发布了它。您的问题是 woocommerce 的购物车数组中没有 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;

}

关于wordpress - 隐藏运输选项 Woocommerce,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17409112/

相关文章:

php - 使用删除和添加操作对 Woocommerce Storefront header 的内容重新排序

php - woocommerce_order_status_completed 未触发

wordpress - 管理媒体库中的子文件夹

wordpress - 如何将媒体文件 http 重定向到 https?

javascript - WordPress - 多个指向同一 URL 的菜单链接处于事件状态

wordpress - WooCommerce 在结帐页面上编辑错误消息

html - wordpress自定义分类法分隔符

php - 这个样式表是从哪里加载的?

php - 注册后 Woocommerce 重定向

php - Woocommerce 商店页面自定义模板