从逗号分隔的订单ID中获取有效的WooCommerce订阅
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了从逗号分隔的订单ID中获取有效的WooCommerce订阅相关的知识,希望对你有一定的参考价值。
尝试使用wcs_get_subscriptions
功能来检索订阅信息以创建可打印标签。
我让插件在查询字符串中传递以逗号分隔的订单ID列表到脚本中,但是我不确定如何将ID字符串传递到函数中:
这是我的实际代码:
$subscriptions = wcs_get_subscriptions( array(
'subscriptions_per_page' => -1,
'subscription_status' => array('active'),
'post_id' => array(123,456,789)
));
foreach($subscriptions as $sub){
echo $sub->get_shipping_city();
}
答案
您的代码中有一些错误:
- 参数
post_id
不存在并且没有效果。 - 您可以使用有效参数
order_id
,但只能处理一个订单ID。
现在代替使用内置函数wcs_get_subscriptions()
,可以使用较轻的SQL查询从特定的订单ID仅获取所需的订阅:
// Your targeted orders IDS (in a coma separated string, not an array)
$targeted_orders_ids = '123,456,789';
global $wpdb;
// get all subscriptions IDS
$subscriptions_ids = $wpdb->get_col( $wpdb->prepare( "
SELECT ID FROM {$wpdb->prefix}posts
WHERE post_type = 'shop_subscription'
AND post_status = 'wc-active'
AND post_parent IN %s;
", ) );
global $wpdb;
// The SQL query (get active subscriptions data from specific orders IDs)
$subscriptions_ids = $wpdb->get_col( $wpdb->prepare( "
SELECT ID FROM {$wpdb->prefix}posts
WHERE post_type = 'shop_subscription'
AND post_status = 'wc-active'
AND post_parent IN (%s);
", $targeted_orders_ids ) );
// Loop through subscriptions Ids
foreach($subscriptions_ids as $subscription_id){
// Get an instance of the WC_Subscription object
$subscription = new WC_Subscription( $subscription_id );
// Unprotected data in an accessible array
$data = $subscription->get_data();
// Get the shipping city
$shipping_city = $data['shipping']['city'];
echo '<p>' . $shipping_city . '</p>'; // Display the shipping city
// print_r( $data ); // Display the subscription raw data array (if needed)
}
经过测试和工作
以上是关于从逗号分隔的订单ID中获取有效的WooCommerce订阅的主要内容,如果未能解决你的问题,请参考以下文章