This code snippet is based on the meta key product_access. It uses the following two conditions to update the WP Query based on this custom meta key defined in the WooCommerce products.
Prerequisites – To make the following functionality work you must add the product_access meta key to the products. You can do this via ACF or custom meta boxes etc.
Case 1: No meta key is present
If the product_access meta key is not defined in the product then it means this product is available to all users.
Case 2: Meta is present
If the meta key product_access is present and has some value, then we can check that value. In this example we are assuming that if it values is 0 then the product can be viewed by all users and if its value is 1 then it can be viewed by logged-in users only.
//Hide specific products for non logged in users in woocommerce
function rp_hide_product_non_logged_in_users( $query ) {
if ( ! is_admin() && $query->is_main_query() && !is_user_logged_in()) {
$meta_query = $query->get( 'meta_query' ) ?: array();
$meta_query[] = array(
'relation' => 'OR',
array(
'key' => 'product_access',
'compare' => 'NOT EXISTS',
),
array(
'key' => 'product_access',
'value' => '0',
'compare' => '=',
)
);
$query->set( 'meta_query', $meta_query );
}
}
add_action( 'pre_get_posts', 'rp_hide_product_non_logged_in_users' );
Note – This code snippet will not work with custom ajax based queries, for that you have to integrate this custom meta_query in your custom WP Queries.
Whether you're facing website issues or struggling with code implementation, our team is here to assist. Hire us to get your website back on track.
Hire Us