sebas sebas - 2 months ago 12
PHP Question

Displaying a custom message containing the category link of first product added to cart

On WooCommerce, I want to show a custom message at the top of the cart page that contains the category link of the first product added to cart.

This is the message:


Add more T-shirts from
{LINK TO CATEGORY OF FIRST PRODUCT ADDED TO CART}
and get a discount!


How can I achieve this? Any idea?

Thanks

Answer

Here is a custom function that will show your custom message on cart page, with the category archive pages link for the first product added to cart.
If a product without a category is added to cart, nothing is displayed.
Optionally you can also display it on checkout page (uncommenting last line).

Here is this code:

function cart_custom_message() {
    if( !WC()->cart->is_empty ){

        //Iterating each item in the cart
        foreach ( WC()->cart->get_cart() as $item ) {

            // Get the product categories object of the current item
            $categories_obj = get_the_terms( $item['product_id'], 'product_cat' );
            if($categories_obj) break; // when an item has a product category, stops the loop
        }
        if($categories_obj) {
            //Iterating each category of the first item
            foreach ( $categories_obj as $category ) {
                break; // stop the loop to on the first category
            }
            $category_id = $category->term_id; // the category id
            $category_name = $category->name; // the category name
            $category_slug = $category->slug; // the category slug
            $category_url = get_term_link( $category_slug, 'product_cat' ); // the link to category archive pages

            // Your message (translatable)
            $message = __("Add more T-shirts from <a href='$category_url'><strong>$category_name</strong></a> category and get a discount!", "your_theme_domain");
            echo "<div class='woocommerce-info'>$message</div>";
        }
    }
}
// Display message on cart page
add_action('woocommerce_before_cart', 'cart_custom_message'); 
// Display message on checkout page (optionally, if needed, uncomment the line below) 
// add_action('woocommerce_before_checkout_form', 'cart_custom_message', 5); 

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

This code is tested and fully functional.


References: