phpwordpresswoocommercecartnotice

Display a notice in cart page if specific products are in WooCommerce cart


how can we make this function below to check multiple product ids instead of just one id, how can we convert it to array ?

add_action( 'woocommerce_before_cart', 'bbloomer_find_product_in_cart' );
    
function bbloomer_find_product_in_cart() {
  
   $product_id = 17285;
  
   $product_cart_id = WC()->cart->generate_cart_id( $product_id );
   $in_cart = WC()->cart->find_product_in_cart( $product_cart_id );
  
   if ( $in_cart ) {
  
      $notice = 'DON\'t Forget to Apply the discount coupon code you received to complete purchasing with the discounted price';
      wc_print_notice( $notice, 'notice' );
  
   }
  
}

We tried $product_ids = array("17285", "17302"); // but it doesn't work

we also tried this but not working too

add_filter( 'woocommerce_before_cart', 'ts_woocommerce_quantity_selected_numbe', 10, 2 );
function ts_woocommerce_quantity_selected_numbe( $product ) {
    $product_ids = array("15757", "15758"); // Here the array of product Ids

    if ( in_array( $product->get_id(), $product_ids ) ) {
        // In cart
        if ( ! is_cart() ) {
            $notice = 'DON\'t Forget to Apply the discount coupon code you received to complete purchasing with the discounted price';
      wc_print_notice( $notice, 'notice' );
        } 
    }
}

Solution

  • To check cart items for one or multiple product Ids, displaying a notice, use instead:

    add_action( 'woocommerce_before_cart', 'found_product_in_cart_display_message' );
    function found_product_in_cart_display_message() {
        $product_ids = array(17285, 17302); // Array or product ids
    
        // Loop through cart items
        foreach ( WC()->cart->get_cart() as $item ) {
            if ( array_intersect( $product_ids, array($item['product_id'], $item['variation_id']) ) ) {
                // Display a notice
                wc_print_notice( __("Don't forget to apply the discount coupon code you received to complete purchasing with the discounted price."), 'notice' );
                break; // Stop the loop
            }
        }
    }
    

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