phpwordpresswoocommerceconditional-statementswoocommerce-memberships

Conditional to check a page access


I have a Wordpress Memberships website that is built on WooCommerce with WooCommerce Memberships plugin to restrict certain pages to members only.

Some of those pages are "drip-fed"... ie. Access to those pages opens 3 days after purchase, etc. I have set this up in WooMemberships.

I am trying to simply do a PHP conditional check to see if the current user has access to a certain page.

I have found this code piece in the docs: wc_memberships_is_post_content_restricted()

However, I have been unable to make it work.

Is there a code snippet which will basically do a PHP IF statement on whether the current user has access to a certain page (using page ID)?

eg:

if ( current_user_has_access(page_ID) ) 
{ 
    //DO SOMETHING 
}
else
{ 
    //DON'T 
}

Solution

  • You will have to Replace (in the conditions):

    1. $page_id by your page ID number (for example: is_page(42))
    2. $membership_plan by the slug of the plan ('plan_slug') or related post ID.

    The conditions:

    You can remove some of the conditions, if not needed, and fine tune for your needs.

    if( wc_memberships_is_post_content_restricted() && is_page($page_id) && wc_memberships_is_user_active_member( $membership_plan ) ) {
    
        // do something
    
    } else {
    
        // don't
    
    }
    

    --- Update ---

    The only function related to restriction and (or) time access are:

    1) wc_memberships_restrict( $content, $membership_plans, $delay, $exclude_trial )
    just like shortcode [wcm_restrict] (so not useful)…

    2) wc_memberships_get_user_access_time( $user_id, $target, $action, $gmt ): Parameters

    $user_id  // for a logged 'user ID'
    $target   : array('post' => id, 'product' => id) // content_type and content_id
    $action   : 'view' or 'purchase' // Type of access (products only)<br>
    $gmt =>   : true  or  false // (selection of the time zone)
    // Returns user access start timestamp (in site timezone) for content or a product
    

    Reference: WooCommerce Memberships Function Reference