Show WooCommerce products only to multiple authorized user roles

不问归期 提交于 2019-12-11 05:22:28

问题


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.


回答1:


As you have 2 arrays to compare:

  • your 2 custom roles (in an array)
  • the current user roles (that is an array)

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.



来源:https://stackoverflow.com/questions/57630819/show-woocommerce-products-only-to-multiple-authorized-user-roles

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!