Created
August 21, 2013 12:22
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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