簡體   English   中英

根據 WooCommerce 中的用戶元數據顯示或隱藏運輸方式

[英]Show or hide shipping methods based on user meta data in WooCommerce

我有一個代碼可以為非批發客戶隱藏運費,請幫我重做,我需要為批發客戶隱藏運費選項。

/**
 * Removes shipping methods for non-wholesale customers.
 * Please be sure to clear your WooCommerce store's cache.
 * Adjust 'flat_rate:2' to match that of your wholesale shipping method.
 */
 
function my_wcs_remove_shipping_non_wholesale( $rates, $package ){
    global $current_user;

    $is_wholesale = get_user_meta( $current_user->ID, 'wcs_wholesale_customer', true );

    if ( ! $is_wholesale ) {
        foreach( $rates as $method ) {
            if ( $method->id == 'flat_rate:2' ) {
                unset( $rates[$method->id] );           
            }
        }
    }
    
    return $rates;
}
add_filter( 'woocommerce_package_rates', 'my_wcs_remove_shipping_non_wholesale', 10, 2 );

您不需要有 2 個函數,一個用於 Wholesale 客戶,另一個用於非 Wholesale 客戶……您可以將兩者合並到同一個函數中,如下所示:

add_filter( 'woocommerce_package_rates', 'shipping_methods_based_on_wholesale_customer', 10, 2 );
function shipping_methods_based_on_wholesale_customer( $rates, $package ){
    $is_wholesale = get_user_meta( get_current_user_id(), 'wcs_wholesale_customer', true );
    
    // Set the shipping methods rate ids in the arrays:
    if( $is_wholesale ) {
        $shipping_rates_ids = array('flat_rate:1', 'flat_rate:4'); // To be removed for NON Wholesale users
    } else {
        $shipping_rates_ids = array('flat_rate:2'); // To be removed for Wholesale users
    }

    // Loop through shipping rates fro the current shipping package
    foreach( $rates as $rate_key => $rate ) {
        if ( in_array( $rate_key, $shipping_rates_ids) ) {
            unset( $rates[$rate_key] ); 
        }
    }
    
    return $rates;
}

代碼位於活動子主題(或活動主題)的 functions.php 文件中。 它應該有效。

保存代碼后不要忘記清空購物車,以刷新緩存的運輸數據

所以對於每個人,比如我,代碼不起作用的地方。 在@Howard E 的幫助下,這里是調整后的代碼 2022,現在可以使用:

add_filter( 'woocommerce_package_rates', 'shipping_methods_based_on_wholesale_customer', 10, 2 );
function shipping_methods_based_on_wholesale_customer( $rates, $package ) {
   $user  = wp_get_current_user();
   $roles = (array) $user->roles;
   // Set the shipping methods rate ids in the arrays.
   if ( ! in_array( 'wholesale_customer', $roles, true ) ) {
      $shipping_rates_ids = array( 'flat_rate:10', 'flat_rate:7' ); // To be removed for NON Wholesale users.
   } else {
      $shipping_rates_ids = array( 'flat_rate:13', 'flat_rate:15' ); // To be removed for Wholesale users.
   }
   // Loop through shipping rates from the current shipping package.
   foreach ( $rates as $rate_key => $rate ) {
      if ( in_array( $rate_key, $shipping_rates_ids, true ) ) {
         unset( $rates[ $rate_key ] );
      }
   }
   return $rates;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM