Henrique Vilela
Henrique Vilela

Reputation: 23

Get all WooCommerce subscriptions

I a need to create a wordpress template to collect all Woocommerce subscriptions, but I'm having trouble with the documentation. I need to know which files to import and which function to call.

Thank you in advice.

Upvotes: 2

Views: 13968

Answers (2)

LoicTheAztec
LoicTheAztec

Reputation: 254473

Update - You can use multiple ways:

  1. The built-in function wcs_get_subscriptions() which accepts specific arguments. In your case, to get all subscriptions, you will use:

    $subscriptions = wcs_get_subscriptions(['subscriptions_per_page' => -1]);

You will get an array of Subscription protected objects where you can use on each object the WC_Data get_data() method, to access the data:

$subscriptions = wcs_get_subscriptions(['subscriptions_per_page' => -1]);

// Loop through subscriptions protected objects
foreach ( $subscriptions as $subscription ) {
    // Unprotected data in an accessible array
    $data = $subscription->get_data();
 
    print_r( $data ); // Display the subscription raw data array
}

Related: Get Subscription Product author of a Woocommerce subscription


  1. You can also use a SQL query to get all subscriptions

A SQL query can be lighter and allows more filtering. This way you can get only the required data in a more effective way.

As subscriptions are a Wordpress custom post type, You can get all subscriptions IDs first. Then in a foreach loop you will be able to get the WC_subscription object.

global $wpdb;

// get all subscriptions IDS
$subscriptions_ids = $wpdb->get_col("
    SELECT ID  FROM {$wpdb->prefix}posts 
    WHERE post_type LIKE 'shop_subscription'
");

// Loop through subscriptions Ids
foreach($subscriptions_ids as $subscription_id){
    // Get an instance of the WC_Subscription object
    $subscription = new WC_Subscription( $subscription_id );

    $data = $subscriptions->get_data();
 
    print_r( $data ); Display the subscription raw data (unprotected accessible array)
}

Then with the $subscription object and the $subscription_id you will be able to do what you want, using WC_Subscription methods to get the desired data or the using subscription ID on dedicated functions.


Official developer Documentation:

Upvotes: 8

Andrew Schultz
Andrew Schultz

Reputation: 4243

You can use the built in function wcs_get_subscriptions($args) and pass the following $args

$args = array( 'subscriptions_per_page' => -1 );

$subscriptions = wcs_get_subscriptions( $args );

You can even filter by subscription status also in the arguments.

Upvotes: 3

Related Questions