This code displays all customers billing emails from all orders on admin orders page, and I need to remove all duplicates from results.
If customer purchases something more times and creates more orders with the same email, display it only one time:
add_action( 'load-edit.php', function(){
$screen = get_current_screen();
if ( 'edit-shop_order' === $screen->id ) {
add_action( 'in_admin_footer', function() {
$args = array(
'limit' => 9999,
'return' => 'ids',
'status' => 'completed'
);
$query = new WC_Order_Query( $args );
$orders = $query->get_orders();
echo '<div style="background-color: #aaa; padding: 10px; margin-bottom: 50px;"><h3>All customer emails</h3>';
echo '<form><textarea rows="8" style="width: 100%;" onclick="this.select()">';
foreach( $orders as $order_id ) {
$order = wc_get_order( $order_id );
echo $order->get_billing_email() . ', ';
}
echo '</textarea></form></div>';
});
add_action( 'admin_footer', function() {
echo '<style>#wpfooter{position: relative !important; top: -50px;}</style>';
} );
}
});
CodePudding user response:
You can use in_array(), and if it doesn't already exist display it. Then add it to the array, so that it exists in the next loop.
So you get:
// Initialize
$billing_emails = array();
// Loop
foreach( $orders as $order_id ) {
// Getters
$order = wc_get_order( $order_id );
$billing_email = $order->get_billing_email();
// Checks if a value exists in an array
if ( ! in_array( $billing_email, $billing_emails ) ) {
// Output
echo $billing_email;
// Push to array
$billing_emails[] = $billing_email;
}
}
Note: it is not necessary to use 'return' => 'ids'
. By default order objects are returned, so that the use of wc_get_order( $order_id )
is not necessary.