如何隐藏除 woocommerce 中的用户组之外的所有用户组的特定运输方式

问题描述 投票:0回答:1

在我们的网上商店,我们希望利用某些用户群体来获得好处,其中之一就是在运输方式上享受 50% 的折扣。因此,我制定了一种具有 50% 折扣的运输方式,并使用 PHP 代码来隐藏用户组“订阅者”的常规运输方式。现在的问题是,我想对其余访客(包括“访客”或未分配给任何用户组的人)隐藏 50% 折扣的送货方式。

这是一段代码:

add_filter( 'woocommerce_package_rates', 'ts_hide_specific_shipping_method_based_on_user_role', 100, 2 );
function ts_hide_specific_shipping_method_based_on_user_role( $rates, $package ) {
    // Here define the shipping rate ID to hide
    $targeted_rate_id    = 'flat_rate:1'; // The shipping rate ID to hide
    $targeted_user_roles = array( 'subscriber');  // The user roles to target (array)
    $current_user  = wp_get_current_user();
    $matched_roles = array_intersect($targeted_user_roles, $current_user->roles);
    if( ! empty($matched_roles) && isset($rates[$targeted_rate_id]) ) {
        unset($rates[$targeted_rate_id]);
    }
    return $rates;
}

问题是,这解决了我的问题的一半,即为订阅者隐藏常规送货方式,但现在向所有其他访客显示 50% 折扣的送货方式。我该如何解决这个问题?

我已经尝试过调整用户组,但主要问题是大多数访问者没有分配到用户组,但我不知道如何在代码中定位他们。

php woocommerce
1个回答
0
投票

您将需要一个

else
分支,并且需要删除相应的项目:

    if( ! empty($matched_roles) && isset($rates[$targeted_rate_id]) ) {
        unset($rates[$targeted_rate_id]);
    } else {
        unset($rates[$your_key_here]);
    }

在上面我使用了

$your_key_here
,因为我缺乏关于在其他情况下需要从费率中隐藏什么的信息。但您需要弄清楚这一点,或者提供更多关于您到底想避免显示什么的信息。

© www.soinside.com 2019 - 2024. All rights reserved.