Wordpress store is using WooCommerce, and I have a small purchase note that I need to appear on WooCommerce Checkout, but only when a certain product is being purchased.
I have added a custom message that now appears below the Place Order button.
However its showing up no matter what is in the cart.
This is the code I currently have in place:
add_action( 'woocommerce_after_checkout_form', 'allclean_add_checkout_content', 12 );
function allclean_add_checkout_content() {
echo '<div class="checkoutdisc">Custom message appears here fine.</div>';
}
Is there a simple code that I can add before this line, that makes it only apply when a certain category product is in the cart?
Thanks
Here we check that we have a product item in cart with this special category. If the condition is matched (in one of the items of the cart), the message is displayed.
Here is the code:
add_action( 'woocommerce_after_checkout_form', 'allclean_add_checkout_content', 12 );
function allclean_add_checkout_content() {
// set your special category name, slug or ID here:
$special_cat = 'special_category';
$bool = false;
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
$item = $cart_item['data'];
if ( has_term( $special_cat, 'product_cat', $item->id ) )
$bool = true;
}
// If the special cat is detected in one items of the cart
// It displays the message
if ($bool)
echo '<div class="checkoutdisc">This is Your custom message displayed.</div>';
}
You can also use an array of products Ids instead of a product category...
In this case the code will be a little bit different:
add_action( 'woocommerce_after_checkout_form', 'allclean_add_checkout_content', 12 );
function allclean_add_checkout_content() {
// set your products IDs here:
$product_ids = array( 31, 68, 87, 124);
$bool = false;
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
$item = $cart_item['data'];
if ( in_array( $item->id, $product_ids ) )
$bool = true;
}
// If the special cat is detected in one items of the cart
// It displays the message
if ($bool)
echo '<div class="checkoutdisc">This is Your custom message displayed.</div>';
}
This code goes in function.php file of your active child theme (or theme) or also in any plugin file.
This code is tested and works.
I think you need to check the cart contents.
add_action( 'woocommerce_after_checkout_form', 'allclean_add_checkout_content', 12 );
function allclean_add_checkout_content() {
$cart = WC()->cart;
foreach ( $this->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
if ( has_term( 'special-category', 'product_cat', $_product->id ) ){
echo '<div class="checkoutdisc">Your custom message.</div>';
}
}
}