Search code examples
phpajaxwordpresswoocommerceshortcode

WooCommerce shortcode to ajaxify message that display: "Buy X more products to get a discount"


After a deep search I created a WooCommerce shortcode. The purpose of this is to display a "Buy X more products to get a discount" message.

My code:

add_shortcode('check', 'custommessage');
function custommessage() {
    $items_count = WC()->cart->get_cart_contents_count();
    $min_count   = 6;

    if( $items_count < $min_count ){
        echo sprintf('%s products more for discount' , $min_count - $items_count );
    }
}

On WooComerce cart page, after adding X products to the cart or removing the quantity it works and refreshes automatically the message

But when I put the shortcode (on side cart) it does not auto refresh the X count. Although it is also AJAX driven.

Any advice how i can solve this?


Solution

  • To ajaxify your message so it updates when an item is added/removed (via ajax) use the woocommerce_add_to_cart_fragments filter hook

    So you get:

    function custom_message() {
        // Initialize
        $message = __( 'Default message', 'woocommerce' );
        
        // True
        if ( WC()->cart ) {
            // Get number of items in the cart.
            $items_count = WC()->cart->get_cart_contents_count();
            $min_count   = 6;
    
            if ( $items_count < $min_count ) {
                $message = sprintf( __( '%s products more for discount', 'woocommerce' ), $min_count - $items_count );
            } else {
                $message = __( 'Some message', 'woocommerce' );
            }
        }
        
        return $message;
    }
    
    // Refreshing on cart ajax events
    function filter_woocommerce_add_to_cart_fragments( $fragments ) {    
        $fragments['div.display-message'] = '<div class="display-message">' . custom_message() . '</div>';
        
        return $fragments;        
    }
    add_filter( 'woocommerce_add_to_cart_fragments', 'filter_woocommerce_add_to_cart_fragments', 10, 1 );
    

    1) Then to display this via a shortcode, use:

    function display_my_message() {
        return '<div class="display-message">' . custom_message() . '</div>';
    } 
    // Register shortcode
    add_shortcode( 'display_message', 'display_my_message' );
    

    SHORTCODE USAGE

    In an existing page:

    [display_message]

    Or in PHP:

    echo do_shortcode("[display_message]");

    OR

    2) To display the message via any desired hook (in this example I show 2 hooks. 1 on the cart page and 1 on the single product page, adapt to your needs). Use:

    // Display message via the desired hooks
    function display_message() {
        echo '<div class="display-message">' . custom_message() . '</div>';
    }
    add_action( 'woocommerce_before_shop_loop', 'display_message', 10, 0 );
    add_action( 'woocommerce_before_add_to_cart_form', 'display_message', 10, 0 );