问题
I am using WooCommerce subscriptions.
How can I get all subscriptions (with start date and end date) in a lists from one specific date to another date?
Example 01/09/2016 to 15/09/2016
Thanks
回答1:
Here is an example of a function that will display a list of all active subscriptions from one date to another, in a formatted html table. In this example, you will get for each subscription: the subscription ID, the date, the customer ID and the customer name (You can customize the code to get what you want).
So this function has 2 date parameters. For usage and specifications see the section at the end.
The function code:
function active_subscription_list($from_date=null, $to_date=null) {
// Get all customer orders
$subscriptions = get_posts( array(
'numberposts' => -1,
'post_type' => 'shop_subscription', // Subscription post type
'post_status' => 'wc-active', // Active subscription
'orderby' => 'post_date', // ordered by date
'order' => 'ASC',
'date_query' => array( // Start & end date
array(
'after' => $from_date,
'before' => $to_date,
'inclusive' => true,
),
),
) );
// Styles (temporary, only for demo display) should be removed
echo "<style>
.subscription_list th, .subscription_list td{border:solid 1px #666; padding:2px 5px;}
.subscription_list th{font-weight:bold}
.subscription_list td{text-align:center}
</style>";
// Displaying list in an html table
echo "<table class='shop_table subscription_list'>
<tr>
<th>" . __( 'Number ID', 'your_theme_domain' ) . "</th>
<th>" . __( 'Date', 'your_theme_domain' ) . "</th>
<th>" . __( 'User ID', 'your_theme_domain' ) . "</th>
<th>" . __( 'User Name', 'your_theme_domain' ) . "</th>
</tr>
";
// Going through each current customer orders
foreach ( $subscriptions as $subscription ) {
$subscription_id = $subscription->ID; // subscription ID
$subscription_date = array_shift( explode( ' ', $subscription->post_date ) ); // Date
$subscr_meta_data = get_post_meta($subscription->ID);
$customer_id = $subscr_meta_data['_customer_user'][0]; // customer ID
$customer_name = $subscr_meta_data['_billing_first_name'][0] . ' ' . $subscr_meta_data['_billing_last_name'][0];
echo "</tr>
<td>$subscription_id</td>
<td>$subscription_date</td>
<td>$customer_id</td>
<td>$customer_name</td>
</tr>";
}
echo '</table>';
}
This code goes in function.php file of your active child theme (or theme) or also in any plugin file.
USAGE (example):
You will have to respect this numerical date format: YEAR-MONTH-DAY
$from_date = '2016-06-19'; // start date
$to_date = '2016-09-21'; // End date
active_subscription_list($from_date, $to_date);
This will display a list of all active subscriptions from 2016-06-19 to 2016-09-21…
This code is tested and works.
来源:https://stackoverflow.com/questions/39596477/woocommerce-get-active-subscriptions-in-a-list-between-start-end-date