duanji1056 2016-09-23 15:42
浏览 18
已采纳

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

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

  • 写回答

1条回答 默认 最新

  • doushi1964 2016-09-23 17:43
    关注

    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:

    展开全部

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部