Получить список всех клиентов, которые купили что-то в Woocommerce

Как я могу получить список клиентов, которые хотя бы что-то купили, и, если возможно, заказать их по количеству заказов? Из того, что я понял _order_count Мета-ключ существует и устанавливается на номер заказа, размещенного как целое число, если они разместили заказ.

Этот запрос игнорирует количество заказов и просто показывает всех пользователей.

$args = array(
'role' => 'customer',
'number' => -1,
'order' => 'ASC',
'orderby' => 'meta_value',
'meta_query' => array(
array(
'key'     => '_order_count',
'value'   => array(''),
'compare' => 'NOT IN'
)
)
);

$query = new WP_User_Query($args);

Это таблица, которая будет отображать информацию о том, сколько пользователь потратил и сколько заказов он разместил

<?php if (! empty($query->get_results())) : ?>

<table class="table">

<thead>
<tr>
<th data-sort="string">Name</th>
<th data-sort="string">Email</th>
<th data-sort="float">Total spent (<?php echo get_option('woocommerce_currency'); ?>)</th>
<th data-sort="int">Order placed</th>
</tr>
</thead>

<tbody>

<?php foreach ($query->get_results() as $user) : ?>

<?php $customer = new WP_User($user->ID); ?>

<tr>
<td><?php echo $user->display_name; ?></td>
<td><?php echo $user->user_email; ?></td>
<td><?php echo wc_get_customer_total_spent($user->ID); ?></td>
<td>
<?php
$customer_orders = get_posts(array(
'numberposts' => -1,
'meta_key'    => '_customer_user',
'meta_value'  => $user->ID,
'post_type'   => wc_get_order_types(),
'post_status' => array('wc-pending', 'wc-processing', 'wc-completed') //array_keys(wc_get_order_statuses()),
));
echo count($customer_orders);
?>
</td>
</tr>

<?php endforeach; ?>

</tbody>
</table>

<?php endif; ?>

2

Решение

Попробуйте следующий код, который использует очень легкий SQL-запрос для получения идентификаторов $ customer. Для подсчета заказов клиентов вы можете использовать специальную функцию wc_get_customer_order_count(),

<?php
global $wpdb;
$customer_ids = $wpdb->get_col("SELECT DISTINCT meta_value  FROM $wpdb->postmeta
WHERE meta_key = '_customer_user' AND meta_value > 0");
print_pr($customer_ids);
$currency = ' (' . get_option('woocommerce_currency') . ')';
if (sizeof($customer_ids) > 0) : ?>
<table class="table">
<thead>
<tr>
<th data-sort="string"><?php _e("Name", "woocommerce"); ?></th>
<th data-sort="string"><?php _e("Email", "woocommerce"); ?></th>
<th data-sort="float"><?php _e("Total spent", "woocommerce"); echo $currency; ?></th>
<th data-sort="int"><?php _e("Orders placed", "woocommerce"); ?></th>
</tr>
</thead>
<tbody>
<?php foreach ($customer_ids as $customer_id) :
$customer = new WP_User($customer_id); ?>
<tr>
<td><?php echo $customer->display_name; ?></td>
<td><?php echo $customer->user_email; ?></td>
<td><?php echo wc_get_customer_total_spent($customer_id); ?></td>
<td><?php echo wc_get_customer_order_count($customer_id); ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php endif; ?>

Проверено и работает.

пользователей meta_key _order_count а также _order_total не существует до WC_Customer_Data_Store get_order_count() а также get_total_spent() Методы запускались один раз для каждого клиента. Также связанные мета значения также обновляются, когда эти методы выполняются для клиента.

Функции wc_get_customer_total_spent() а также wc_get_customer_order_count() выполнить эти методы и обновить соответствующие метаданные пользователя.

3

Другие решения

Других решений пока нет …