Get all WooCommerce subscriptions

有些话、适合烂在心里 提交于 2019-12-11 04:35:37

问题


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.


回答1:


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


2) 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:

  • Introduction to Subscriptions Developer Documentation
  • Subscriptions Data Structures & Storage



回答2:


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.



来源:https://stackoverflow.com/questions/45701599/get-all-woocommerce-subscriptions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!