Skip to content

Instantly share code, notes, and snippets.

@Lonsdale201
Last active November 28, 2023 12:42
Show Gist options
  • Select an option

  • Save Lonsdale201/24c66ac2f324de52d8585916a5d21a96 to your computer and use it in GitHub Desktop.

Select an option

Save Lonsdale201/24c66ac2f324de52d8585916a5d21a96 to your computer and use it in GitHub Desktop.
JetEngine - Custom Macro - Current user Membership
// place the code in the child theme functions.php or a custom code snippets plugin.
// how to use
// Create a new User Query in the Query builder.
// Go to the Include/exclude section
// Click the Dynamic tag icon, and select the WC Current User membership macro. In the text field write your membership ID and done.
// Include or Exclude can apply this macro.
// This macro will return the selected user id
// If the membership ID not exist, or not have user with selected ID membership active, will return
// My all Gist: https://gist.github.com/Lonsdale201
// if need multiple version: https://gist.github.com/Lonsdale201/726c1ddfe03b18145759a94357477fb6
add_action( 'jet-engine/register-macros', function(){
class WC_Current_User_Membership extends \Jet_Engine_Base_Macros {
public function macros_tag() {
return 'wc_current_user_membership';
}
public function macros_name() {
return 'WC Current User Membership';
}
public function macros_args() {
return array(
'membership_id' => array(
'label' => 'Membership ID',
'type' => 'text',
'default' => '',
),
);
}
public function macros_callback( $args = array() ) {
$membership_id = !empty( $args['membership_id'] ) ? intval( $args['membership_id'] ) : 0;
if ( $membership_id <= 0 || !function_exists( 'wc_memberships_get_user_memberships' )) {
return 'Invalid Membership ID';
}
if (!wc_memberships_get_membership_plan( $membership_id )) {
return 'No such Membership Plan exists';
}
$user_ids = array();
$users = get_users( array( 'fields' => 'ids' ) );
foreach ( $users as $user_id ) {
$memberships = wc_memberships_get_user_memberships( $user_id, array( 'status' => array( 'active' ) ) );
foreach ( $memberships as $membership ) {
if ( $membership->get_plan_id() == $membership_id ) {
$user_ids[] = $user_id;
break;
}
}
}
if ( empty( $user_ids ) ) {
return 'No users found for the given Membership ID';
}
return implode( ',', $user_ids );
}
}
new WC_Current_User_Membership();
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment