获取 WooCommerce 会员计划的所有活跃用户

Get all active users for a membership plan in WooCommerce

我正在使用 Wordpress 4.9.4 版和 WooCommerce WooCommerce Memberships plugin

如何获取特定会员计划 ($memberships) 的所有用户?

有钩子还是我应该使用原始查询?

在文档上,它说计划/会员资格是 post 类型,所以我试图查询这个 table:

SELECT jsu.id, jsu.user_email, jsu.display_name, jsp.post_title, jsp.post_type FROM `wp_users` jsu
LEFT JOIN `wp_posts` jsp ON (jsu.id = jsp.post_author)
LEFT JOIN `wp_usermeta` jsum ON (jsu.id = jsum.user_id)
WHERE jsp.post_title IN ($memberships) AND post_type = 'wc_membership_plan'

但是我没有得到想要的结果。

我对你的 SQL 进行了一些修改,并在实用函数中设置了代码:

function get_active_members_for_membership($memberships){
    global $wpdb;

    // Getting all User IDs and data for a membership plan
    return $wpdb->get_results( "
        SELECT DISTINCT um.user_id, u.user_email, u.display_name, p2.post_title, p2.post_type
        FROM {$wpdb->prefix}posts AS p
        LEFT JOIN {$wpdb->prefix}posts AS p2 ON p2.ID = p.post_parent
        LEFT JOIN {$wpdb->prefix}users AS u ON u.id = p.post_author
        LEFT JOIN {$wpdb->prefix}usermeta AS um ON u.id = um.user_id
        WHERE p.post_type = 'wc_user_membership'
        AND p.post_status IN ('wcm-active')
        AND p2.post_type = 'wc_membership_plan'
        AND p2.post_title LIKE '$memberships'
    ");
}

此代码在您的活动子主题(或主题)的 function.php 文件中。 已测试并有效。

用法:

// Replace 'My Membership' by your targeted membership name.
$users_data = get_active_members_for_membership('My Membership');

// Test raw output
echo '<pre>'; print_r( $users_data ); echo '</pre>';