Skip to content

Instantly share code, notes, and snippets.

@marklchaves
Last active February 23, 2022 22:45
Show Gist options
  • Save marklchaves/c7bb7535b5c899c28853dddc0a470df3 to your computer and use it in GitHub Desktop.
Save marklchaves/c7bb7535b5c899c28853dddc0a470df3 to your computer and use it in GitHub Desktop.
Filter the WooCommerce product query based on logged-in role and product attribute.
<?php // Ignore this first line when copying to your child theme's functions.php file.
function filter_product_query_on_attribute_and_role($tax_query, $query)
{
// Step 1: Filter the role.
if (wp_get_current_user()->roles[0] != 'wholesale') return $tax_query; // Logged-in except wholesale can see.
// More examples:
// 1. Filter all roles except for wholesale.
// if ( wp_get_current_user()->roles[0] == 'wholesale' ) return $tax_query; // Only a logged-in wholesale role can see.
// 2. Filter anyone who's *not* logged in.
// if ( is_user_logged_in() ) return $tax_query; // Only logged in can see.
// 3. Filter selected roles.
//if ( in_array( wp_get_current_user()->roles[0], array( 'administrator', 'buyer', 'shop_manager' ) ) ) return $tax_query; // Only admins, buyers, and shop managers can see.
// Step 2: Filter the product attribute.
// Here's our example product attribute
// - Name: Test
// - Slug: test
// - Values: test-1 | test-2
// Set the taxonomy of your product attribute (custom taxonomy).
$taxonomy = 'pa_test'; // Should start with "pa_" in WooCommerce.
// Set the value of the product attribute you want to exclude.
$terms = array('test-1'); // Don't show any products with test-1 for the Test attribute.
// Filter the taxonmy query using the criteria above.
$tax_query[] = array(
'taxonomy' => $taxonomy,
'field' => 'slug', // Can be a 'term_id', 'slug' or 'name'.
'terms' => $terms,
'operator' => 'NOT IN', // Excluded
);
return $tax_query;
}
add_filter('woocommerce_product_query_tax_query', 'filter_product_query_on_attribute_and_role', 10, 2);
/**
* You can add the PHP code snippet to your child theme's functions.php file
* or with a third-party plugin such as My Custom Functions or Code Snippets.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment