I'm trying to integrate WooCommerce Memberships with some custom Advanced Custom Fields code and a Timber/Twig Wordpress set up. I found a good function here for checking if a user can access the content. Unfortunately I came across some difficulties when my administrator role didn't even have access. In my debugging I found that when calling wc_memberships_get_user_memberships
with the current user ID, it would return NULL on my administrator user. I've since added a check to see if the user is a shop_manager or administrator and return true always for them.
function can_user_access_content($user_id,$post_id){
// bail if Memberships isn't active
if ( ! function_exists( 'wc_memberships' ) ) {
return true;
}
$user = get_user_by('id',$user_id);
if ( in_array( 'administrator', (array) $user->roles ) || in_array( 'shop_manager', (array) $user->roles ) ) {
//The user has the "administrator" or "shop manager" role
return true;
}
//check if there's a force public on this content
if(get_post_meta($post_id,'_wc_memberships_force_public',true)=='yes') return true;
$args = array( 'status' => array( 'active' ));
$plans = wc_memberships_get_user_memberships( $user_id, $args );
$user_plans = array();
foreach($plans as $plan){
array_push($user_plans,$plan->plan_id);
}
$rules = wc_memberships()->get_rules_instance()->get_post_content_restriction_rules( $post_id );
if(!count($rules)) {
return true;
}
foreach($rules as $rule){
if(in_array($rule->get_membership_plan_id(), $user_plans)){
return true;
}
}
return false;
}
Is this a correct way to achieve this? I also am struggling on how to find a way to retrieve the appropriate "Content unavailable" message for the page/post/product to display. I am falling back to showing the regular post content if the content is restricted, which would normally have the messages filtered in my WC Memberships, but this doesn't appear to always work. Would love something a little more foolproof.
Any help would be really appreciated!