Показывать количество заказов по статусам и по пользовательскому полю ACF в Woocommerce


Я работаю над своего рода внутренним "плагином", чтобы показать, сколько заказов у меня в настоящее время с разделением по статусам и менеджеру аккаунта. Поэтому я хотел бы представить его в виде таблицы, например:

Account Manager | No of pending orders | No of canceled orders etc

У меня есть такой фрагмент кода:

function display_woocommerce_order_count( $atts, $content = null ) {
    $args = shortcode_atts( array(
        'status' => 'completed',
    ), $atts );
    $statuses    = array_map( 'trim', explode( ',', $args['status'] ) );
    $order_count = 0;
    foreach ( $statuses as $status ) {
        // if we didn't get a wc- prefix, add one
        if ( 0 !== strpos( $status, 'wc-' ) ) {
            $status = 'wc-' . $status;
        }
        $order_count += wp_count_posts( 'shop_order' )->$status;
    }
    ob_start();
    echo number_format( $order_count );
    return ob_get_clean();
}
add_shortcode( 'wc_order_count', 'display_woocommerce_order_count' );

Кроме того, я видел этот код, но я не уверен, как его использовать:

public function get_customer_total_order() {
    $customer_orders = get_posts( array(
        'numberposts' => - 1,
        'meta_key'    => '_customer_user',
        'meta_value'  => get_current_user_id(),
        'post_type'   => array( 'shop_order' ),
        'post_status' => array( 'wc-completed' )
    ) );

    $total = 0;
    foreach ( $customer_orders as $customer_order ) {
        $order = wc_get_order( $customer_order );
        $total += $order->get_total();
    }

    return $total;
}

, который добавляет короткий код для отображения в общем номере заказа, но без разбивки на менеджера по работе с клиентами. Через ACF я создал пользовательское поле под названием "handlowiec" и назначил его на экран заказа. Как заставить это работать?

Author: LoicTheAztec, 2018-04-26

1 answers

Следующий код будет подсчитывать заказы по статусу для идентификатора менеджера текущего счета, соответствующего полю ACF "handlowiec":

enter image description here

Таким образом, вам придется присвоить каждому заказу идентификатор менеджера аккаунта:

enter image description here

Код функции с очень легким SQL-запросом (на основе wp_count_posts() функции WordPress):

function display_woocommerce_order_count( $atts, $content = null ) {
    $args = shortcode_atts( array(
        'status' => 'completed, processing, on-hold, cancelled',
        'handlowiec' => ''
    ), $atts );

    // Formatting the order statuses for the SQL query
    $statuses = $data = [];
    $statuses_array = array_map( 'trim', explode( ',', $args['status'] ) );

    foreach ( $statuses_array as $status ) {
        if ( 0 !== strpos( $status, 'wc-' ) )
            $statuses[] = 'wc-' . $status;
    }
    $statuses = implode("','", $statuses);

    ## -- 1. The SQL Query -- ##

    global $wpdb;
    $handlowiec_query = $join_postmeta = $output = '';

    // Handling the Account Manager ID (optionally)
    if( $args['handlowiec'] !== '' ){
        $join_postmeta = "INNER JOIN {$wpdb->prefix}postmeta pm ON p.ID = pm.post_id";
        $handlowiec_query = "AND meta_key like 'handlowiec' AND meta_value = ";
        $handlowiec_query .= $args['handlowiec'];
    }

    $results = $wpdb->get_results("
        SELECT post_status, COUNT( * ) AS num_posts
        FROM {$wpdb->prefix}posts as p
        $join_postmeta
        WHERE post_type = 'shop_order'
        AND post_status IN ('$statuses')
        $handlowiec_query
        GROUP BY post_status
    ");

    ## -- 2. Formatting the Output -- ##

    // Loop through each order status count
    foreach($results as $result){
        $status = str_replace( 'wc-', '', $result->post_status );
        $orders_count = (int) $result->num_posts;

        if( $orders_count > 0 )
            $data[] =  ucfirst($status) . ' ' . _n( 'order', 'orders', $orders_count ) . ': ' . $orders_count;
    }
    if( $args['handlowiec'] !== '' )
        $output = 'Account Manager ID ' . $args['handlowiec'] . ' | ';
    else
        $output = 'All Account Managers | ';

    if( sizeof($data) > 0 )
        $output .= implode( ' | ', $data );
    else
        $output .= 'No results';

    return '<p>' . $output . '</p>';
}
add_shortcode( 'wc_order_count', 'display_woocommerce_order_count' );

Вводится код function.php файл вашей активной дочерней темы (или активной темы). Испытанный и работает.


ИСПОЛЬЗОВАНИЕ:

1) Без "Идентификатора менеджера аккаунта" (для всех менеджеров):

 echo do_shortcode("[wc_order_count]");

Вы получите что-то вроде:

All Account Managers | On-hold orders: 2 | Processing orders: 7 | …

2) С определенным "Идентификатором менеджера аккаунта":

echo do_shortcode("[wc_order_count handlowiec='5']");

Вы получите что-то вроде:

Account Manager ID 5 | On-hold order: 1 | Processing orders: 3 | …

Вы также можете использовать, как и раньше, аргумент status, чтобы указать, какой статус заказов будет задействован в выводе...

 4
Author: LoicTheAztec, 2018-05-06 05:00:58