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

Viewed 1225

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 Answers

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;
Related