Discover in this tutorial how to show the number of Stripe active subscribers using its API and a shortcode in WordPress.
If you or any of your clients have an online business that uses Stripe as a payment gateway and is a lover of Open Metrics, this will surely interest you.
In this tutorial you will learn how to show the number of active subscribers you have in Stripe, using its fantastic API, and keep it always updated wherever you want on the web.
Here’s how to do it:
Instructions to create a shortcode to display the number of active Stripe subscribers
1. Create the shorcode
Add the following code at the end of functions.php or in your functionality plugin:
To see this and another 1097 code snippets of this website, login or subscribe here.
In this code you use the Stripe library and the secret API key stored by Restrict Content Pro.
If you are using another plugin (Easy Digital Downloads, Gravity Forms…) you would have to change that part and adapt it to it. If you want me to prepare a tutorial with some variation just let me know.
The Stripe API doesn’t have an endpoint where you can get the total number of active subscribers, so you have to get all of them (using a loop with the autoPagingIterator
function), and add them up.
It is worth noting that Stripe subscriptions can have several statuses:
- active = active
- trialing = testing
- canceled = canceled (but not expired)
- incomplete = incomplete payment (retry)
- incomplete_expired = incomplete payment (not retried)
- past_due = when payment date has passed
- unpaid = not paid
In this case, you are accounting for the first 3, but if you see that there is a discrepancy with your Stripe dashboard it is because it also takes past_due into account. If you want to include them just add || $subscriber->status === 'past_due'
to the conditional.
Depending on the project, this request can be quite “heavy”, so inside the shortcode you create and use a transient to cache the result for a day (although you can modify it to your liking). This way you make sure that the result is displayed immediately.
2. Insert the shortcode where you want
Finally, just type [active_subscribers]
where you want it to be displayed.
You can use the block editor to create the layout you want and enter the shortcode to display the total revenue, for example.
Conclusions
Now you know how to show the number of active subscribers in Stripe and that this data is always updated at any point of the website using a shortcode.
Even if you are not going to use this snippet to display the data publicly, you can use it to create a dashboard where you can add all the relevant data of your business.
In addition, with small variations you can customize it to fit 100% to your needs.
Now you just have to put it into practice. 😉
Any questions? I read you in the comments.
And if you want to give me any suggestion for future tutorials, leave it in the contact form. Advantages of being a subscriber. 😉