Woocommerce products editable by their author for specific user role

泪湿孤枕 提交于 2021-02-08 04:17:12

问题


I have different users registered on my WordPress website with different roles. Apart from the rest of users, I want to allow advertisers (users with advertiser role - advertiser is a custom role that I have created) to place their own products on my site and also manage them. But they need to be limited only to manage (create, edit and delete) their own products, not of others.

So far, I have tried the following code but it seems to be not valid. I am sure I can accomplish my goal using pre_get_posts action and the following function can help me but I need some help in resolving the issues with this code. I am not sure about the post type of products.

Here is the code that I am trying to accomplish my goal with:

function show_specific_advertiser_products( $query ) {
    $current_user = wp_get_current_user();
    if ( is_admin() && in_array ($query->get( 'post_type'), array( 'woocommerce_products' ) ) && !user_can( $current_user, 'administrator' ) ) {

        $query->set( 'author__in', $current_user->ID );
    }
}
add_action( 'pre_get_posts', 'show_specific_advertiser_products' );

Any help will highly be appreciated.


回答1:


The error in your code comes from the post_type… for woocommerce products it's simply product. You will have to replace administrator by your custom user role.

So try the following instead:

add_action( 'pre_get_posts', 'show_specific_advertiser_products' );
function show_specific_advertiser_products( $query ) {
    $user = wp_get_current_user();
    if ( is_admin() && $query->get( 'post_type') === 'product' && in_array('administrator', $user->roles) ) {
        $query->set( 'author', $user->ID );
    }
}

Code goes in function.php file of your active child theme (or active theme). It should works.



来源:https://stackoverflow.com/questions/54886051/woocommerce-products-editable-by-their-author-for-specific-user-role

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