Display only products from the logged in author on WooCommerce admin products list

戏子无情 提交于 2021-01-28 04:59:27

问题


Is there a way, by which this Admin product dashboard shows only the products created by the logged-in user?

I am trying manage_{$post->post_type}_posts_custom_column function but cannot move much

E.g. I want something like this

add_action( 'manage_product_posts_custom_column', 'custom_column_content', 10, 2 );
function custom_column_content( $column, $product_id ){
        if( logged in user==Product Author){
            Display product;
        }
        else{
            Dont display product
        }
}

回答1:


The manage_product_posts_custom_column hook is made to manipulate the columns content from admin products list.

So you need instead to alter the product query from admin products list using:

add_action( 'pre_get_posts', 'admin_pre_get_posts_product_query' );
function admin_pre_get_posts_product_query( $query ) {
    global $pagenow;

    // Targeting admin product list
    if( is_admin() && 'edit.php' == $pagenow && isset($_GET['post_type']) && 'product' === $_GET['post_type'] ) {
        $query->set( 'author', get_current_user_id() ); // Only displays the products created by the current user
    }
}

Code goes in functions.php file of your active child theme (or active theme). Tested and works.

Now you will have only the products belonging to the current user ID, as we filter products by logged in author.


Allowing a specific user role to view all products:

If you want to allow only "administrator" user role to view all products, you will insert in the code, just after global $pagenow; the following lines:

    // Allow administrator user roles
    if( current_user_can( 'administrator' ) ) return;


来源:https://stackoverflow.com/questions/62153785/display-only-products-from-the-logged-in-author-on-woocommerce-admin-products-li

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