How do I get all the users with an active subscription in Commerce 2? I want to be able to filter entries by subscribed users.

  • Is this in the CMS or on the front end? – Jason Mayo Oct 8 '18 at 10:24
  • @JasonMayo front end. – Simon Kuran Oct 8 '18 at 15:02

I solved this by creating a simple plugin.

use craft\db\Query;

class MyPluginVariable
      public function allActivelySubscribedUserIds()
           $subscribedUserIds = (new Query())

            // Create array of just user IDs
            $subscribedUserIds = array_column($subscribedUserIds, 'userId');

            return $subscribedUserIds;

I my case I needed to display all entries authored by users that are currently subscribed. In my template I used the variable like this:

{% set subscribedUserIds = craft.MyPlugin.allActivelySubscribedUserIds %}

{% set entries = craft.entries()
|improve this answer|||||

Not Commerce 2, but in Commerce 3, like this:

{% set userIdsWithSubscriptions = craft.subscriptions.limit(null).all()|group('userId')|keys %}
{% set users = craft.users.id(userIdsWithSubscriptions).all() %}

  {% for user in users %}
    <li>{{ user.username }}</li>
  {% endfor %}

Via Nathaniel @ Craft Support (thanks!)

|improve this answer|||||
  • 2
    FYI: this may need some optimization, depending on the scale of your application, like selection of specific columns (.select('userId').column(), instead of .all() | group('userId') | keys), as loading all Element data + instantiating the models can quickly exhaust memory—we've seen major slowdowns after about 1K elements, and out-of-memory errors at 10K. – August Miller Mar 16 at 19:06
  • 1
    Thanks @AugustMiller that's good to add in. I am using a mixture of .with and pagination, but I think I may add in the .select too – iamkeir Mar 18 at 16:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.