Избегайте многократного отображения пользовательского уведомления в WooCommerce Cart - PullRequest
1 голос
/ 24 мая 2019

Я работаю для некоммерческой организации, где люди могут заказать у них информационные брошюры.Брошюры можно заказать по отдельности или в упаковке.Упаковка настроена как один продукт с идентификатором 1076.

Когда клиент заказывает упаковку, он может заказать ее только самостоятельно.

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

Как мне обеспечить, чтобы wc_print_notice() выводил уведомление на странице корзины только один раз?

Вот код, который у меня есть (он собран из нескольких источников, поэтому он, вероятно, неэффективен)

// Remove conditionally cart items based on a specific product (item)
    function remove_cart_items_conditionally( $cart ) {
    // HERE define your specific product ID
    $specific_product_id = 1076; 

    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    $cart_items  = $cart->get_cart(); // Cart items array
    $items_count = count($cart_items); // Different cart items count

    // Continue if cart has at least 2 different cart items
    if ( $items_count < 2 )
        return;

    $last_item    = end($cart_items); // Last cart item data array
    $is_last_item = false; // Initializing

    // Check if the specific product is the last added item
    if ( in_array($specific_product_id, array( $last_item['product_id'], $last_item['variation_id'] ) ) ) {
        $is_last_item = true;
    }

    // Loop through cart items
    foreach ( $cart_items as $cart_item_key => $cart_item ) {
        // Remove all others cart items when specific product ID is the last added to cart
        if ( ! in_array($specific_product_id, array( $cart_item['product_id'], $cart_item['variation_id'] ) ) && $is_last_item ) {
            $cart->remove_cart_item( $cart_item_key );
            wc_print_notice( 'Individual resources have been removed as the full pack already contains all the resources', 'notice' );
        }
    }
}
add_action( 'woocommerce_before_calculate_totals', 'remove_cart_items_conditionally', 10, 1 );

// Disable the add to cart button if specified product is in the cart
function disable_add_to_cart_if_product_is_in_cart ( $is_purchasable, $product ){

    $specific_product_id = 1076;

    // Loop through cart items checking if the product is already in cart
    foreach ( WC()->cart->get_cart() as $cart_item ){
        if ( in_array($specific_product_id, array( $cart_item['product_id'], $cart_item['variation_id'] ) ) ) {
            return false;

        }
    }
    return $is_purchasable;
}
add_filter( 'woocommerce_is_purchasable', 'disable_add_to_cart_if_product_is_in_cart', 10, 2 );

// Change disabled add to cart button popup message to something relevant
function customizing_product_variation_message( $translated_text, $untranslated_text, $domain )
{
    if ( in_array($specific_product_id, array( $cart_item['product_id'], $cart_item['variation_id'] ) ) ) {
        if ($untranslated_text == 'Sorry, this product is unavailable. Please choose a different combination.') {
        $translated_text = __( 'The full pack in the cart already contains this resource', $domain );
        }
    }
    return $translated_text;
}
add_filter( 'gettext', 'customizing_product_variation_message', 10, 3 );

мой код составлен из потоков ответов:

Условно удалить Woocommerceэлементы корзины на основе определенного продукта

Отключить кнопку Woocommerce добавить в корзину, если продукт уже находится в корзине

Настройка сообщения о вариациях продукта для одногостраницы продукта

1 Ответ

0 голосов
/ 24 мая 2019

Вы используете wc_print_notice в цикле, поэтому он будет отображать столько же раз, сколько и цикл.Чтобы преодолеть это, пожалуйста, попробуйте следующий код.

Замените этот раздел кода.Этот код по умолчанию отключит уведомление о вызове.Он включит извещение о вызове только тогда, когда будет выполнен цикл и удален элемент корзины.

// Loop through cart items
    foreach ( $cart_items as $cart_item_key => $cart_item ) {
        // Remove all others cart items when specific product ID is the last added to cart
        if ( ! in_array($specific_product_id, array( $cart_item['product_id'], $cart_item['variation_id'] ) ) && $is_last_item ) {
            $cart->remove_cart_item( $cart_item_key );
            wc_print_notice( 'Individual resources have been removed as the full pack already contains all the resources', 'notice' );
        }
    }

по этому коду, и дайте мне знать результат.

// Loop through cart items
    $enable_notice = false;
    foreach ( $cart_items as $cart_item_key => $cart_item ) {
        // Remove all others cart items when specific product ID is the last added to cart
        if ( ! in_array($specific_product_id, array( $cart_item['product_id'], $cart_item['variation_id'] ) ) && $is_last_item ) {
            $cart->remove_cart_item( $cart_item_key );
            $enable_notice = true;
        }
    }
    if($enable_notice){
        wc_print_notice( 'Individual resources have been removed as the full pack already contains all the resources', 'notice' );    
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...