Make specific products accessible only to a user role in WooCommerce

I am making 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 );
}

}

Thats code will hide product from search. But other users still can access the product detail page from direct link.

Here my code that hide the product single pages (which is not works):

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);
*/
}
}

If I set a redirect script, it says: “Cannot modify header information – headers already sent by …”

I think this will works if I can modify the product query to negative ID number which will trigger the “product not found” page. But I dont know which is the action hook name to do it. Then I may be my code could works using wp action hook like add_action( ‘wp’, ‘wcpp_hide_product_detail’ );. But I dont know the right hook.

Any help is appreciated.

Read more here:: Make specific products accessible only to a user role in WooCommerce

Leave a Reply

Your email address will not be published. Required fields are marked *