as the title suggests, I have to show a custom text in the woocommerce cart, based on the product category added by the customer
// Add a function to show custom text on the cart page
add_action( 'woocommerce_before_cart', 'show_custom_text' );
// Define the function
function show_custom_text() {
// Get the current cart
$cart = WC()->cart;
// Check if the cart is empty
if ( $cart->is_empty() ) {
return;
}
// Create an associative array with the product categories and related texts to display
$categories_and_texts = array(
'1' => 'This is text 1',
'2' => 'This is text 2',
'3' => 'This is text 3',
// Add more categories and lyrics here
);
// Create an empty array to store the categories in the cart
$categories_in_cart = array();
// Iterate over all the items in the cart
foreach ( $cart->get_cart() as $cart_item ) {
// Get the current product
$product = $cart_item['data'];
// Get product categories
$product_categories = wp_get_post_terms( $product->get_id(), 'product_cat' );
// Iterate over all product categories
foreach ( $product_categories as $product_category ) {
// Get the category slug
$category_slug = $product_category->slug;
// Check if the category is among those defined in the associative array
if ( array_key_exists( $category_slug, $categories_and_texts ) ) {
// Add the category to the array of categories in the cart, if not already present
if ( ! in_array( $category_slug, $categories_in_cart ) ) {
$categories_in_cart[] = $category_slug;
}
}
}
}
// Check if there are any categories in the cart
if ( ! empty( $categories_in_cart ) ) {
// Show a message before custom texts
echo '<p>Attention, you have added products from the following categories to your cart:</p>';
// Iterate over all the categories in the cart
foreach ( $categories_in_cart as $category ) {
// Show the text corresponding to the category
echo '<p>' . $categories_and_texts[$category] . '</p>';
}
}
}
I’m trying this function but it doesn’t seem to work
I’d like to show the text also in the thankyou page and in the order email
Thank you