1

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
1

I solved this by creating a simple plugin.

use craft\db\Query;

class MyPluginVariable
{
      public function allActivelySubscribedUserIds()
      {
           $subscribedUserIds = (new Query())
                ->select('userId')
                ->from(['{{%commerce_subscriptions}}'])
                ->distinct()
                ->all();

            // 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()
    .authorId(subscribedUserIds)
    .all()
%}

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.