Search code examples
phphtmlwoocommercecart

Show Text if Product Exists in Cart


The edit is at ThemeName/WooCommerce/cart/cart.php, line 149.

Extra text will be shown just above the "Coupon code" field if listed product is in the cart. This text is to inform the customer that they are eligible for a coupon (price deduction) if the condition is met.

What I've tried:

<p>
  <?php
    $product_id = $cart_item['variation_id'] > 0 ? $cart_item['variation_id'] : 
             $cart_item['product_id'];

    if($product_id == "15502" || $product_id == "15566" || $product_id == "15567" || 
        $product_id == "18946" || $product_id == "18947" || $product_id == "18948" || 
        $product_id == "16199")
      echo 'You may use the coupon "x" for your free complimentary greeting card!';
  ?>
</p>

There is an empty paragraph of where the text is meant to be displayed, but the code does not work as intended.

What I was expecting: Identify product_id in cart. IF product exists in cart, then display text.


Solution

  • <p>
      <?php
      //Check items in cart
      foreach(WC()->cart->get_cart() as $cart_item){
        $product_id = $cart_item['product_id'];
    }
    
      $x = array(15502, 15566, 15567, 18946, 18947, 18948);
    
      //If this is true, then
      if(in_array($product_id, $x, true)){
        echo 'Insert text here.';
    } 
      ?>
    </p>
    

    For a more functional & automated solution, please read: Auto apply or remove a coupon in Woocommerce cart for a specific product id