仅向多个授权用户角色显示 WooCommerce 产品 [英] Show WooCommerce products only to multiple authorized user roles

查看:56
本文介绍了仅向多个授权用户角色显示 WooCommerce 产品的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试适应"完全隐藏产品来自 WooCommerce 中未经授权的用户" 回答代码还允许多个自定义用户角色查看此产品.我认为实现这一点的最好方法是扩展授权用户功能以包含此用户角色.

I'm trying to adapt "Completely hide products from unauthorized users in WooCommerce" answer code to also allow several custom user roles to view this products. I believe the best way to accomplish this is to expand the authorized user function to include this user roles.

这是我尝试实施但未成功的更改.有人可以说明如何进行吗?

This is the changes that I have tried to implement with no success. Can someone shine a light on how to proceed?

// Conditional function checking for authorized users

function is_authorized_user() {

    if ( is_user_logged_in() ) {

        $user = wp_get_current_user();
        $caps = $user->allcaps;

        if ( ( isset($caps['edit_product']) && $caps['edit_product'] ) ||
        array( 'custom_user_role1', 'custom_user_role2', $user->roles ) )
           return true;
    } else 
        return false;
}

如何使其适用于一系列用户角色,而不仅仅是一个?任何帮助表示赞赏.

How to make it work for an array of user roles, instead of just one? Any help is appreciated.

推荐答案

因为您有 2 个要比较的数组:

As you have 2 arrays to compare:

  • 您的 2 个自定义角色(在数组中)
  • 当前用户角色(即数组)

你可以使用array_intersect() php 函数使其以这种方式工作:

you can use array_intersect() php function to make it work this way:

// Conditional function checking for authorized users
function is_authorized_user(){

    if ( is_user_logged_in() ) {

        $user = wp_get_current_user();
        $caps = $user->allcaps;

        if ( ( isset($caps['edit_product']) && $caps['edit_product'] ) || 
        array_intersect( ['custom_user_role1', 'custom_user_role2'], $user->roles ) ) {
            return true;
        }

        return false; 
    } 
    else {
        return false; 
    }
}

它现在应该适用于多个用户角色.

It should work now for multiple user roles.

这篇关于仅向多个授权用户角色显示 WooCommerce 产品的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆