I want to create an alert when I add a product with the shipping class "FRESH" to the shopping cart with Woocommerce.
I have created this function although I know that they contain 2 Hooks because I have not found the correct one yet, the alert appears even when I do not add a product with the "FRESH" category.
My idea that it may be misdirected was to verify once a product added to the cart if there is one with "FRESH", and that there is only one but it is not well raised.
My wish would be when I add a product to the cart if that product I am adding has the shipping class "Fresh" to notify the customer with a PopUp / alert that says for example. "You have added a FRESH product."
thanks for your help
function action_woocommerce_after_add_to_cart_form_alert_if_cart_add_fresh($product) {
$shippingclass_array = array( 'fresh' );
$cart_contain_product_fresh_for_alert = 0;
foreach ( WC()->cart->get_cart() as $cart_item_key => $values )
{
$shipping_class = get_the_terms( $values['product_id'], 'product_shipping_class' );
$quantity = $values['quantity'];
if ($quantity < 2 ){
if ( isset( $shipping_class[0]->slug ) && in_array( $shipping_class[0]->slug, $shippingclass_array ) ) {
$cart_contain_product_fresh_for_alert ++;
}
}
}
if($cart_contain_product_fresh_for_alert === 1 ){
$freshInCart = true;
?>
<script>
jQuery(function($){
alert('Se ha añadido un producto fresco a su carrito');
});
</script>
<?php
}
};
add_action( 'woocommerce_after_add_to_cart', 'action_woocommerce_after_add_to_cart_form_alert_if_cart_add_fresh');
add_action( 'woocommerce_after_add_to_cart_button', 'action_woocommerce_after_add_to_cart_form_alert_if_cart_add_fresh', 10, 1 );