phpwordpresswoocommercewoocommerce-subscriptions

Get woocommerce user active memberships - extract data from php multi array


array (
0 => 
WC_Memberships_User_Membership::__set_state(array(
 'id' => 52330,
 'plan_id' => 18952,
 'plan' => 
WC_Memberships_Membership_Plan::__set_state(array(
   'id' => 18952,
   'name' => 'Level 2 Access Until June',
   'slug' => 'level-2-access-until-june',
   'post' => 
  WP_Post::__set_state(array(
     'ID' => 18952,
     'post_author' => '8',
     'post_date' => '2017-09-11 11:05:13',
     'post_date_gmt' => '2017-09-11 15:05:13',
  )),
   'access_method_meta' => '_access_method',
   'rules' => 
  array (
  ),
)),
 'user_id' => '5213',
 'status' => 'wcm-active',
 'post' => 
WP_Post::__set_state(array(
   'ID' => 52330,
   'post_title' => 'Auto Draft',

)),
 'product' => NULL,
 'renewal_login_token_meta' => '_renewal_login_token',
 'locked_meta' => '_locked',
)),
 1 => 
 WC_Memberships_User_Membership::__set_state(array(
 'id' => 28639,
 'plan_id' => 27786,
 'plan' => 
WC_Memberships_Membership_Plan::__set_state(array(
   'id' => 27786,
   'name' => 'Level 1 – Ethical and Professional Standards',
   'slug' => 'level-1-ethical-and-professional-standards',
   'post' => 
  WP_Post::__set_state(array(
     'ID' => 27786,
     'post_author' => '8',
     'post_mime_type' => '',
     'comment_count' => '0',
     'filter' => 'raw',
  )),
   'access_method_meta' => '_access_method',
   'email_content_meta' => '_email_content',
   'rules' => 
  array (
  ),
)),
 'user_id' => '5213',
 'status' => 'wcm-active',
 'post' => 
WP_Post::__set_state(array(
   'ID' => 28639,
   'post_author' => '5213',
   'post_date' => '2017-11-27 21:41:06',
   'filter' => 'raw',
)),
 'product' => NULL,
 'type' => 'manually-assigned',
 'locked_meta' => '_locked',
 )),
);

I have this array given by woocommerce method: wc_memberships_get_user_active_memberships($user_id);

I need to extract out the name of the memberships the user has, it must be in a loop as the user can have multiple memberships. I am looking to get back name = Level 2 Access Until June, Level 1 – Ethical and Professional Standards


Solution

  • From what you've posted, I would try this:

    $memberships_info = wc_memberships_get_user_active_memberships($user_id);
    
    foreach ($memberships_info as $membership) {
        echo $membership['plan']['name'];
    }
    

    From the woocommerce docs, it looks like you can specify what status of active memberships. So you might want to do that to include all membership types:

    $args = array( 
        'status' => array( 'active', 'complimentary', 'pending' ),
    );  
    $memberships_info = wc_memberships_get_user_active_memberships($user_id, $args); // adding the args bit to get all memberships
    
    foreach ($memberships_info as $membership) {
        echo $membership['plan']['name'];
    }
    

    Woocommerce docs: https://docs.woocommerce.com/document/woocommerce-memberships-function-reference/