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 at 10:24
  • @JasonMayo front end. – Simon Kuran Oct 8 at 15:02
up vote 1 down vote accepted

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 acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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