[英]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.