Search code examples
phpwordpresswoocommercebackenduser-roles

Display only pending products based on user role in WooCommerce admin product list


I would like to display only pending products in WooCommerce admin product list for shop manager and hide all trash

Using CSS I was able to partially hide items that I don't want to be visible:

.current,
.draft,
.publish,
.search-box,
.byorder,
.tablenav.top,
    .page-title-action {
display: none;
    visibility:hidden;
}

This is not sufficient so I also use:

function exclude_other_author_products($query) {
  $current_user = wp_get_current_user();
  if (in_array('administrator', $current_user->shop_manager)
    return $query;
if ($query->query['post_type'] == 'product' && $query->is_main_query()) {
    $query->set('author__in', $current_user->ID);
}
 }

add_action('pre_get_posts', 'exclude_other_author_products');

However, this produces a critical error: syntax error, unexpected token "return"

Any advice?


Solution

  • You can use post_status

    • publish - a published post or page
    • pending - post is pending review
    • draft - a post in draft status
    • auto-draft - a newly created post, with no content
    • future - a post to publish in the future
    • private - not visible to users who are not logged in
    • inherit - a revision. see get_children.
    • trash - post is in trashbin.

    Note: Both the user roles and the post statuses consist of an array. So several can be added, separated by a comma

    so you get:

    function action_pre_get_posts( $query ) {   
        global $pagenow, $post_type;
        
        // Targeting admin product list
        if ( $query->is_admin && $pagenow === 'edit.php' && $post_type === 'product' ) {
            // Get current user
            $user = wp_get_current_user();
        
            // Roles
            $roles = (array) $user->roles;
            
            // Roles to check
            $roles_to_check = array( 'shop_manager' );
            
            // Compare
            $compare = array_diff( $roles, $roles_to_check );
        
            // Result is empty
            if ( empty ( $compare ) ) {
                // Set "post status"
                $query->set( 'post_status', array( 'pending' ) );
                
                /* OPTIONAL
                // Set "posts per page"
                $query->set( 'posts_per_page', 20 );
    
                // Set "paged"
                $query->set( 'paged', ( get_query_var('paged') ? get_query_var('paged') : 1 ) );
                */
            }
        }
    }
    add_action( 'pre_get_posts', 'action_pre_get_posts', 10, 1 );