Home > Blockchain >  Hide products from WooCommerce shop and archive pages if product author is not Admin
Hide products from WooCommerce shop and archive pages if product author is not Admin

Time:12-15

This is not related who the current user is. What I'm trying to accomplish is to hide any products on the shop and archive pages if the product's author is Admin. I tried searching on here and other places, but anything I find is related to if the current user is logged in or is admin. Any assistance is greatly appreciated!

function hide_product_by_user_role( $query ) {
    
    
     $authors = ( array ) $product->authors; // obtaining product author -- this is wrong
    
    
    if ( $query->is_main_query() && is_woocommerce() &&  $authors[0] != 'administrator' ) {
        
        .... what do I do here?
    }
}

add_action( 'pre_get_posts', 'hide_product_by_user_role' );

CodePudding user response:

  1. Find the admin(s) id(s)
  2. Include them in the query
add_action('pre_get_posts', 'hide_product_by_user_role', 999);

function hide_product_by_user_role($query){ 

    $users_args = array(
        'role__in' => array('Administrator'),
        'fields'   => 'ID'
    );

    $admins_ids = get_users($users_args);

    if ($query->is_main_query() && is_woocommerce() ) {
        $query->set('author__in', $admins_ids);
    }
}

Reference:
https://developer.wordpress.org/reference/classes/wp_query/#parameters

  • Related