根据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 );

解决方法

您不需要具有两个功能,一个用于批发客户,另一个用于非批发客户……您可以将两个功能合并为同一功能,如下所示:

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文件中。应该可以。

保存代码后,别忘了清空购物车,以刷新缓存的运输数据

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...