从 WooCommerce 订单获取以逗号分隔的电子邮件字符串

问题描述 投票:0回答:1

这是我从每个订单获取电子邮件地址的代码:

function callback() {

    $args = array('return'  => 'ids' );
    
    $query = new WC_Order_Query( $args );

    $orders = $query->get_orders();

    $emails_array = [];
    
    foreach( $orders as $order_id ) {
    
    $order          = wc_get_order( $order_id );
    $order_ids      = $order->get_id();
    $billing_email  = $order->get_billing_email();

    $emails_array[] = $billing_email;
    
    echo implode( ',', $emails_array );
     
    //echo json_encode( $billing_email ); 

   // implode(',', $billing_email );
     

  }
}

输出这个:

[email protected]@example.com

我需要在每个电子邮件地址之间添加逗号并生成如下列表:

[email protected],[email protected]

我尝试过 json_encode、implode、explode 和存储像这样的数组 $billing_email[] = some 但不知道该怎么做。

更新:我已更新代码,但在电子邮件列表中出现重复项。

当我使用 json_encode 时,我得到这个;

[email protected]”“[email protected]

php arrays woocommerce orders implode
1个回答
0
投票

在 emails 数组上使用

array_unique()
,以避免重复的电子邮件,然后您可以使用
implode()
来获取一串逗号分隔的电子邮件,不重复。

我对代码进行了简化和优化:

function callback() {
    $emails = array(); // Initialize
    $args   = [ 'limit' => -1, 'type' => 'shop_order' ];

    // Loop through orders objects
    foreach( wc_get_orders($args) as $order ) {
        $emails[] = $order->get_billing_email();
    }

    echo implode( ',', array_unique( $emails ) );
}

已测试且有效。


注:

为了避免错误,请始终指定 WooCommerce Order type(自定义帖子类型),查询订单时,如果有退款,就会抛出错误。

请参阅

wc_get_orders
WC_Order_Query
> 参数文档。

© www.soinside.com 2019 - 2024. All rights reserved.