I need to make a plugin to hide specific product category only for a user role
add_action( 'woocommerce_product_query', 'wcpp_hide_product' );
function wcpp_hide_product( $q ) {
//if main query, skip
if ( ! $q->is_main_query() ) return;
//jika admin, skip
if(is_admin()) return;
//if user is not logged in, or dont have PRIVATE_MEMBER roles hide the product
$current_user = wp_get_current_user();
if(!isset($current_user->roles) || !in_array('PRIVATE_MEMBER', $current_user->roles)){
$tax_query = (array) $q->get( 'tax_query' );
$tax_query[] = array(
'taxonomy' => 'product_cat',
'field' => 'id',
'terms' => 'PRIVATE_CATEGORY',
'operator' => 'NOT IN'
);
$q->set( 'tax_query', $tax_query );
}
}
This code is hiding search for the product. However, other users can still access the product detail page directly from the link. I also tried to hide the product single pages but it did not work
add_action( 'woocommerce_before_single_product', 'wcpp_hide_product_detail' );
//add_action( 'pre_get_posts', 'wcpp_hide_product_detail' );
function wcpp_hide_product_detail() {
if(is_admin()) return;
global $post;
$terms = get_the_terms( $post->ID, 'product_cat' );
if(empty($terms)) return;
$is_private=false;
foreach($terms as $term){
if('PRIVATE_CATEGORY'==$term->term_id){
$is_private = true;
break;
}
}
if(!$is_private) return;
$current_user = wp_get_current_user();
if(!isset($current_user->roles) || !in_array('PRIVATE_MEMBER', $current_user->roles)){
//need do something here, but not works
//maybe redirect
//wp_redirect(home_url());
/* or like set 404
global $wp_query;
$wp_query->set_404();
status_header(404);
*/
}
}
Please help