【问题标题】:Disable WooCommerce payment gateway for guests and specific user roles为客人和特定用户角色禁用 WooCommerce 支付网关
【发布时间】:2020-09-27 11:22:13
【问题描述】:

我已为我网站中的一个用户角色(“客户”)禁用发票付款方式,但现在我需要向此规则添加另一个用户角色(“企业”),但我不知道如何让它起作用。当我添加第二个角色时,代码完全停止工作,并最终向所有用户显示网关。

这是我用来禁用网关的代码:

我对 PHP 不是很有经验,所以任何帮助都将不胜感激。 如果您有机会更正我的代码以适应用例,我将不胜感激。

add_filter( 'woocommerce_available_payment_gateways', 'payment_gateway_disable_private' );

 function payment_gateway_disable_private( $available_gateways ) {

    $user = wp_get_current_user();

    if ( isset( $available_gateways['igfw_invoice_gateway'] ) && !is_user_logged_in() || isset( $available_gateways['igfw_invoice_gateway'] ) && in_array('customer', $user->roles)  ) {
        unset( $available_gateways['igfw_invoice_gateway'] );
    }

   return $available_gateways;

}

想法?

【问题讨论】:

  • in_array — 检查数组中是否存在值,如果要比较多个值,则不应将字符串与数组进行比较,而应将数组与数组进行比较。见this答案(多角色检查的部分以及如何完成)
  • 我还可以提请您注意(在您编辑您的问题之后)SO 不是“代码编写服务”。我们的想法是开始尝试,而不是让别人为你做这件事。请阅读How do I ask a good question?Stack Overflow question checklist

标签: php wordpress woocommerce payment-gateway user-roles


【解决方案1】:

你的 if 语句有错误(你也可以使用current_user_can() 函数作为用户角色) 比如:

add_filter( 'woocommerce_available_payment_gateways', 'payment_gateway_disable_private' );
function payment_gateway_disable_private( $available_gateways ) {
    if ( ( ! is_user_logged_in() || current_user_can('customer') || current_user_can('business') ) 
    && isset( $available_gateways['igfw_invoice_gateway'] ) ) {
        unset( $available_gateways['igfw_invoice_gateway'] );
    }
   return $available_gateways;
}

或使用global $current_user;array_intersect() 函数:

add_filter( 'woocommerce_available_payment_gateways', 'payment_gateway_disable_private' );
function payment_gateway_disable_private( $available_gateways ) {
    global $current_user;

    // Here define your user roles
    $user_roles = array( 'customer', 'business' );

    if ( ( ! is_user_logged_in() || array_intersect( $current_user->roles, $user_roles ) ) 
    && isset( $available_gateways['igfw_invoice_gateway'] ) ) {
        unset( $available_gateways['igfw_invoice_gateway'] );
    }
   return $available_gateways;
}

现在应该可以更好地工作了。

【讨论】:

    猜你喜欢
    • 2015-08-26
    • 2017-04-20
    • 2020-09-16
    • 1970-01-01
    • 2019-03-12
    • 2018-11-15
    • 2012-04-10
    • 2012-12-01
    • 2021-06-07
    相关资源
    最近更新 更多