问题
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