Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I detect if user has subscribed Memberpress product already

How can I detect if user has already bought a memberpress product.

I'm searching something like this:

if(have_subscription){ 
   //code to add button
}else{
   // code to add something else
}
like image 856
Shamppi Avatar asked Apr 20 '15 09:04

Shamppi


2 Answers

This should be pretty straight forward using MemberPress' built in capabilities:

if(current_user_can('memberpress_authorized')) {
  // Do authorized only stuff here
}
else {
  // Do unauthorized stuff here
}

MemberPress also adds capabilities for each MemberPress Membership so you could also do something like this:

if(current_user_can('memberpress_product_authorized_123')) {
  // Do authorized only stuff here
}
else {
  // Do unauthorized stuff here
}

In the second example the number 123 is the id of the MemberPress membership.

like image 111
supercleanse Avatar answered Sep 27 '22 23:09

supercleanse


The answer from 2015 didn't work for me but is a top search result. I thought I should share the result of my search here for others in the future.

Also, I think that "product_authorized" capability only checked if a purchase was made, not verifying the expiration date.

So here is how MemberPress determines if active, inactive, or none:

$mepr_user = new MeprUser( $user_id );

if( $mepr_user->is_active() ) {
    // Active
}else if($mepr_user->has_expired()) {
    // Expired
}else {
    // Never a member
}

has_expired() can return true even if the user is active from a separate transaction so don't rely on that alone.

If you need to check a specific membership you can use the following:

$user_id = 123;
$membership_id = 5000;

$mepr_user = new MeprUser( $user_id );

$mepr_user->is_already_subscribed_to( $membership_id ); // true or false

// OR

$mepr_user->is_active_on_membership( $membership_id ); // true or false

is_already_subscribed_to() accepts only a product id

is_active_on_membership() accepts any of: product id, MeprProduct, MeprTransaction, or MeprSubscription

You can also get all of a user's active subscriptions with:

$mepr_user->active_product_subscriptions( 'ids' ); // return array of ids
like image 43
Radley Sustaire Avatar answered Sep 28 '22 01:09

Radley Sustaire