PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, December 28, 2021

[FIXED] Hide products from WooCommerce shop and archive pages if product author is not Admin

 December 28, 2021     woocommerce, wordpress     No comments   

Issue

This is not related to 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' );

Solution

  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



Answered By - Mokhless
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing