[英]Hide specific shipping options based on products or categories in WooCommerce
我的WooCommerce网站使用3种不同的运送类型。
某些产品只能使用选项1进行运输。将这种产品添加到购物车后,我创建的运输类别有助于在购物车中显示选项1,但其他两个选项仍然可见(不允许客户选择以下选项)这个产品)。 通过使用jQuery,我能够隐藏其他两个选项,因为选项1是默认选择。 (因此,很容易基于此隐藏其他两个)。
我遇到的问题是2个隐藏选项仍显示在结帐页面上,我不确定为什么。
这是我在购物车中选择第一个选项时用来隐藏其他两个选项的代码:
jQuery(document.body).ready(function() {
if(jQuery('#shipping_method_0_ced_pps').val() == 'ced_pps')
jQuery('ul#shipping_method li:nth-child(2)').hide();
jQuery('ul#shipping_method li:nth-child(3)').hide();
});
奇怪的是,如果我测试看看结帐页面上是否存在值,我可以发出警报,但是当我使用上述代码时,它根本无法工作。
有人可以提供一些帮助或替代方法吗?
我在这里已经看过了, 这是我不使用jQuery就最接近解决方案的地方。 该解决方案的问题在于,我需要手动将产品ID输入到functions.php文件中。 当产品超过100种时,这是不理想的。
更新了有多种方法,无需使用jQuery:
1)如果产品很少 ,则可以使用以下代码进行定义:
编码:
add_filter( 'woocommerce_package_rates', 'specific_products_shipping_methods', 10, 2 );
function specific_products_shipping_methods( $rates, $package ) {
// HERE set the product IDs in the array
$product_ids = array( 113, 115, 126 );
// HERE set the shipping methods to be removed (like "fat_rate:5")
$method_instances_ids = array('2846', '2851');
$found = false;
// Loop through cart items checking for defined product IDs
foreach( $package['contents'] as $cart_item ) {
if ( in_array( $cart_item['product_id'], $product_ids ) ){
$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;
}
代码进入您的活动子主题(或活动主题)的function.php文件中。 经过测试和工作。
2)如果您有一堆产品 ,最好通过产品类别(或产品标签)来定位这些产品……您可以批量分配它。
在代码中,您将定义:
product_tag
的产品标签) 编码:
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( 'my-category' );
$taxonomy = 'product_cat';
// HERE set the shipping methods to be removed (like "fat_rate:5")
$method_instances_ids = array('2846', '2851');
$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;
}
代码进入您的活动子主题(或活动主题)的function.php文件中。 经过测试和工作。
为了使其适用于产品标签 :
您只需将分类法'product_cat'
替换为'product_tag'
3)如果您有一堆产品 ,还可以创建一个运输类别并将其批量分配给您的产品。 您需要在相关的送货方式中为其设置价格...
您应该需要刷新运输缓存:
1)首先,此代码已保存在您的function.php文件中,并清空购物车…
2)在运送设置中,输入运送区域并禁用运送方法和“保存”。 然后重新启用该运输方法并“保存”。 大功告成
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.