Created
July 31, 2019 20:36
-
-
Save karen-white/d0ef752a7d7e225e9a1276da7b7cc74a to your computer and use it in GitHub Desktop.
This file contains 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
<?php | |
/* | |
Plugin Name: BC4WP > Customer Group Category Visibility | |
Description: Example plugin to hide BC categories based on customer group access | |
Author: BigCommerce | |
Version: 0.5 | |
*/ | |
// Set to -1 to not set a default customer group for visibility | |
// (using 0 will pull in the first customer group from BC) | |
const DEFAULT_CUSTOMER_GROUP_ID = 6; | |
function set_default_customer_group($group, $customer) { | |
if ($customer->get_customer_id() === 0) { | |
return DEFAULT_CUSTOMER_GROUP_ID; | |
} | |
} | |
add_filter('bigcommerce/customer/group_id', 'set_default_customer_group', 10, 2); | |
function filter_categories_based_on_customer_group($sorted_menu_items, $args) { | |
// https://developer.wordpress.org/reference/functions/get_current_user_id/ | |
$current_user_id = get_current_user_id(); | |
$customer = new \BigCommerce\Accounts\Customer($current_user_id); | |
try { | |
$customer_group_info = $customer->get_group()->get_info(); | |
} catch ( \Exception $e ) { | |
wp_die( $e->getMessage() ); | |
} | |
return array_filter($sorted_menu_items, function($item) use ($current_user_id, $customer_group_info) { | |
if ($item->object === 'bigcommerce_category') { | |
// https://developer.wordpress.org/reference/functions/get_term_meta | |
$category_meta = get_term_meta($item->object_id); | |
$bigcommerce_category_id = $category_meta['bigcommerce_id'][0]; | |
// Only show this category if one of the two conditions apply: | |
// 1) The customer group category is blank (is the default fallback) | |
// or | |
// 2a) The customer group category access type is set to 'all' | |
// 2b) The customer group category access type is set to 'specific' and the category is within the categories array | |
return empty($customer_group_info['category_access']) || ($customer_group_info['category_access']['type'] && ($customer_group_info['category_access']['type'] === 'all' || ($customer_group_info['category_access']['type'] === 'specific' && in_array($bigcommerce_category_id, $customer_group_info['category_access']['categories'])))); | |
} | |
// For all other types of menu items, pass them through so they display normally. | |
return true; | |
}); | |
} | |
add_filter('wp_nav_menu_objects', 'filter_categories_based_on_customer_group', 10, 2); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment