woocommercewoocommerce-memberships

WooCommerce Memberships check if a specific user is able to access a specific content


The WooCommerce Membership has some conditionals but I can't combine them to specifically test whether a specific member has access to specific content.

 $post_id = get_the_ID(); // this post is available to access level 'insights' but *not* available to a member with access level 'resources'

 // if post content is restricted
 if ( wc_memberships_is_post_content_restricted($post_id) ) {
 // returns true for *any* restricted content (whether restricted for this member or not)

     // check if user has membership
     $user_id = get_current_user_id(); // this member has access level 'resources' but not 'insights'
     if ( wc_memberships_is_user_active_member( $user_id, 'resources' ) ){
     /// will return *true* dependent on user but *not* dependent on content
         echo "You";
     } else {
         echo 'Not you ';
     }
 }

always returns 'You'

so how do I check whether this user has the access level for this content?

In plain English I think I need to find out what restrictions are placed on the post content but there doesn't seem to be a conditional for that (which is very odd)


Solution

  • After going around the houses several times and with a bit of help from sky verge

    function wc_memberships_user_has_access($post_id) {
    
      if (wc_memberships_is_post_content_restricted() && ! current_user_can( 'wc_memberships_view_restricted_post_content', $post_id ))  {
        return false;
      } else {
        return true;
      }
    
    }
    

    the simply pass the post ID to this function and it returns a Boolean depending on the current user's access to the current post.