Отображать различные уведомления на основе количества заказов клиентов в Woocommerce - PullRequest
0 голосов
/ 05 января 2019

Я ищу легкий способ подсчета всех заказов клиентов со статусом «Завершено» и на основе количества заказов, для отображения различных сообщений с помощью wc_print_notice.

Подсчет работает нормально, но я надеюсь, что у кого-то есть более легкий способ сделать это.

Отображение первого сообщения работает, но оно не показывает 2-е сообщение (когда количество выполненных заказов равно 2 или более).

Идея состоит в том, чтобы распространить это в общей сложности на 10 различных сообщений и предоставить покупателю различные коды скидок во время покупок на сайте.

Надеюсь, посмотрев код, вы поймете, чего я пытаюсь достичь. Итак, что я прошу, так это сочетание ДВУХ вещей;

  1. как мне заставить elseif работать так, чтобы он отображал разные сообщения, а не все сообщения одновременно?

  2. Есть ли более легкий способ подсчета суммы заказа?

Вот мой код:

add_action( 'woocommerce_before_my_account', 'shop_loyalty_program' );
add_action( 'woocommerce_before_shop_loop', 'shop_loyalty_program' );
add_action( 'woocommerce_before_single_product_summary', 'shop_loyalty_program' );

function shop_loyalty_program() {

    $customer = wp_get_current_user();

    // count how many orders by the customer with "completed" status
    // we only count the completed status since completed = paid
    $customer_orders = get_posts( array(
        'numberposts' => -1,
        'meta_key'    => '_customer_user',
        'meta_value'  => get_current_user_id(),
        'post_type'   => 'shop_order',
        'post_status' => 'wc-completed' // only "completed" as completed = paid
    ) );


    // discount counter for our loyalty system
    $first_order = 0;
    $third_order = 2;

    // messages to be shown depending on how many completed orders

    // FIRST ORDER message when 0 orders exist
    $first_order_message = sprintf( 'Hey %1$s 😀 For your first order, we\'ll give you a 10 percent discount and with that we say - WELCOME to our store!', $customer->display_name, $first_order );


    // THIRD ORDER message when 2 orders exist
    $third_order_message = sprintf( 'Hey %1$s 😀 We noticed you\'ve placed more than %2$s orders with us – thanks for being a loyal customer!', $customer->display_name, $third_order );


    // discount control
    if ( count( $customer_orders ) >= $first_order ) {
        wc_print_notice( $first_order_message, 'notice' );
    }

    elseif ( count( $customer_orders ) >= $third_order ) {
        wc_print_notice( $third_order_message, 'notice' );
        }
    }

1 Ответ

0 голосов
/ 05 января 2019

Следующий пересмотренный код должен работать как положено (с гораздо более легким SQL-запросом для подсчета заказов) :

add_action( 'woocommerce_before_my_account', 'shop_loyalty_program' );
add_action( 'woocommerce_before_shop_loop', 'shop_loyalty_program' );
add_action( 'woocommerce_before_single_product_summary', 'shop_loyalty_program' );
function shop_loyalty_program() {
    global $wpdb;

    // Get current WP User Object instance
    $user = wp_get_current_user();

    // Only for logged in users
    if( $user->ID == 0 ) return false;

    // Count customer orders with "Completed" status (Paid)
    $orders_count = $wpdb->get_var( "
        SELECT COUNT(ID) FROM {$wpdb->prefix}posts as p
        INNER JOIN {$wpdb->prefix}postmeta as pm ON p.ID = pm.post_id
        WHERE p.post_status LIKE 'wc-completed' AND p.post_type LIKE 'shop_order'
        AND pm.meta_key LIKE '_customer_user' AND pm.meta_value = {$user->ID}
    " );

     // FIRST ORDER Message (0 orders)
    if ( $orders_count == 0 ) {
        $message = sprintf( __("Hey %s 😀 For your first order, we'll give you a 10 %% discount and with that we say - WELCOME to our store!"), $user->display_name );
    }
    // TWO ORDERS AT LEAST Message (when 2 orders or more exist)
    elseif ( $orders_count >= 2 ) {
        $message = sprintf( __("Hey %s 😀 We noticed you've placed at least 2 orders with us – Thanks for being a loyal customer!"), $user->display_name );
    }

    // Display message
    if ( isset($message) ) {
        wc_print_notice( $message, 'notice' );
    }
}

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

enter image description here


enter image description here

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...