Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
906 views
in Technique[技术] by (71.8m points)

php - Display message based on cart items count in WooCommerce cart

I'd like to display a message in either woocommerce_before_cart or woocommerce_before_cart_table if the total number of items in the cart is less than X, and also display the difference. By items I mean individual quantities not product lines.

How can I add a function that sums the quantities of all items in the cart and displays a message if the total is less than the specified quantity?

Example: Set the number to 30, cart contains a total of 27 items, so a message would say 'If you order 3 more items you can get...' etc. But if the cart already has 30 or more items, then no message needs to show.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

To display a custom message on cart page based on number of cart items count, use the following:

// On cart page only
add_action( 'woocommerce_check_cart_items', 'custom_total_item_quantity_message' );
function custom_total_item_quantity_message() {
    $items_count = WC()->cart->get_cart_contents_count();
    $min_count   = 30;

    if( is_cart() && $items_count < $min_count ){
        wc_print_notice( sprintf( __("If you order %s more items you can get…", "woocommerce"), $min_count - $items_count ), 'notice' );
    }
}

Code goes in function.php file of your active child theme (or active theme). Tested and work.


If using woocommerce_before_cart or woocommerce_before_cart_table the remaining count will not be updated when changing quantities or removing items… Try:

add_action( 'woocommerce_before_cart', 'custom_total_item_quantity_message' );
function custom_total_item_quantity_message() {
    $items_count = WC()->cart->get_cart_contents_count();
    $min_count   = 30;

    if( is_cart() && $items_count < $min_count ){
        echo '<div class="woocommerce-info">';
        printf( __("If you order %s more items you can get…", "woocommerce"), $min_count - $items_count );
        echo '</div>';
    }
}

or:

add_action( 'woocommerce_before_cart_table', 'custom_total_item_quantity_message' );
function custom_total_item_quantity_message() {
    $items_count = WC()->cart->get_cart_contents_count();
    $min_count   = 30;

    if( is_cart() && $items_count < $min_count ){
        echo '<div class="woocommerce-info">';
        printf( __("If you order %s more items you can get…", "woocommerce"), $min_count - $items_count );
        echo '</div>';
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...