Search code examples
phpwordpresswoocommercecheckoutnotice

Add a custom notice for backordered cart items in Woocommerce checkout


I am trying to add an action that will check if there is a product in the cart on backorder and if true display a message before the checkout form. This is what i have so far but it doesn't seem to be working. Am i messing something ?

add_action( 'woocommerce_before_checkout_form', 'checkout_add_cart_notice' );
function checkout_add_cart_notice() {
$message = "Please allow 2-3 weeks for the custom order product.";

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

}

function 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;
}

Solution

  • The following code will display a custom message on checkout page when there is backordered items in cart:

    add_action( 'woocommerce_before_checkout_form', 'backordered_items_checkout_notice' );
    function backordered_items_checkout_notice() {
        $found = false;
    
        foreach( WC()->cart->get_cart() as $cart_item ) {
            if( $cart_item['data']->is_on_backorder( $cart_item['quantity'] ) ) {
                $found = true;
                break;
            }
        }
    
        if( $found ) {
            wc_print_notice( __("Please allow 2-3 weeks for the custom order product.", "woocommerce"), 'notice' );
        }
    }
    

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

    enter image description here