Skip to content
Advertisement

Show message on WooCommerce cart and checkout page when cart contains backorder products

I currently have this code in functions.php in order to display a message on the checkout page saying the customer has backordered products in their cart:

add_action( 'woocommerce_review_order_before_payment', 'es_checkout_add_cart_notice' );
function es_checkout_add_cart_notice() {
    $message = "You have a backorder product in your cart.";

    if ( es_check_cart_has_backorder_product() )
        wc_add_notice( $message, 'error' );

}

function es_check_cart_has_backorder_product() {
    foreach( WC()->cart->get_cart() as $cart_item_key => $values ) {
        $cart_product =  wc_get_product( $values['data']->get_id() );

        if( $cart_product->is_on_backorder() )
            return true;
    }

    return false;
}

What do I need to do to also have this same message display on the CART page? (Before going to Checkout).

Thanks in advance.

Advertisement

Answer

Note 1: I changed the code so that it works with 1 hook on both pages as opposed to using 2 different hooks


Note 2: Notice the use of the notice_type

wc_add_notice( __( $message, 'woocommerce' ), 'notice' ); opposite 'error'.

Ultimately, this is not an error


Note 3: optionally you can remove the ‘proceed_to_checkout’ button (code line is in comment, this doesn’t seem to apply here) (see note 2)

So you get:

function es_add_cart_notice() {
    // Only on cart and check out pages
    if( ! ( is_cart() || is_checkout() ) ) return;
    
    // Set message
    $message = "You have a backorder product in your cart.";
    
    // Set variable
    $found = false;
    
    // Loop through all products in the Cart        
    foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
        // Get an instance of the WC_Product object
        $product = $cart_item['data'];

        // Product on backorder
        if( $product->is_on_backorder() ) {
            $found = true;
            break;
        }
    }

    // true
    if ( $found ) {
        wc_add_notice( __( $message, 'woocommerce' ), 'notice' );
        
        // Removing the proceed button, until the condition is met
        // optional
        // remove_action( 'woocommerce_proceed_to_checkout','woocommerce_button_proceed_to_checkout', 20);
    }

}
add_action( 'woocommerce_check_cart_items', 'es_add_cart_notice', 10, 0 );
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement