显示包含第一个添加到购物车的产品的类别 link 的自定义消息

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

在 WooCommerce 上,我想在购物车页面顶部显示自定义消息,其中包含添加到购物车的第一个产品的类别 link。

这是消息:

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

我怎样才能做到这一点?有什么想法吗?

谢谢

这是一个自定义函数,它将在购物车页面上显示您的自定义消息,第一个添加到购物车的产品的类别存档页面 link。
如果将没有类别的产品添加到购物车,则不会显示任何内容。
您也可以选择在结帐页面上显示它 (取消注释最后一行).

这是这段代码:

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); 

代码进入您的活动子主题(或主题)的 function.php 文件或任何插件文件。

此代码已经过测试且功能齐全。


参考文献: