Skip to content

Instantly share code, notes, and snippets.

@lucasstark
Created August 21, 2013 12:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lucasstark/6293787 to your computer and use it in GitHub Desktop.
Save lucasstark/6293787 to your computer and use it in GitHub Desktop.
Use filters to control who can view and purchase products when using WooCommerce Catalog Visibility Options.
function set_catalog_visibility_user_can_purchase($result, $product){
$result = false; //set the default.
//create an array of roles and their assoicated categories.
$allowed = array(
'customer' => array(
'bakeware',
'appliances',
'category-1',
),
'another-role' => array(
'category-1',
'category-2',
)
);
//get the product categories.
$product_categories = wp_get_post_terms($product->id, 'product_cat', array('fields' => 'slugs'));
//find the first role the user is in and check if any of the categories for the role match any of the product categories.
foreach($allowed as $role => $allowed_categories){
if (current_user_can($role)){
if (count(array_intersect($allowed_categories, $product_categories)) > 0) {
$result = true;
break;
}
}
}
return $result;
}
add_filter('catalog_visibility_user_can_purchase', 'set_catalog_visibility_user_can_purchase', 10, 2);
function set_catalog_visibility_user_can_view_price($result, $product){
$result = false; //set the default.
//create an array of roles and their assoicated categories.
$allowed = array(
'customer' => array(
'bakeware',
'appliances',
'category-1',
),
'another-role' => array(
'category-1',
'category-2',
)
);
//get the product categories.
$product_categories = wp_get_post_terms($product->id, 'product_cat', array('fields' => 'slugs'));
//find the first role the user is in and check if any of the categories for the role match any of the product categories.
foreach($allowed as $role => $allowed_categories){
if (current_user_can($role)){
if (count(array_intersect($allowed_categories, $product_categories)) > 0) {
$result = true;
break;
}
}
}
return $result;
}
add_filter('catalog_visibility_user_can_view_price', 'set_catalog_visibility_user_can_view_price', 10, 2);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment