1
在WooCommerce上,我想在購物車頁面的頂部顯示一條自定義消息,其中包含添加到購物車的第一個產品的分類鏈接。顯示包含第一個產品的分類鏈接的自定義消息添加到購物車
這是消息:
從
{LINK TO CATEGORY OF FIRST PRODUCT ADDED TO CART}
添加更多的T恤,並獲得折扣!
我該如何做到這一點?任何想法?
感謝
在WooCommerce上,我想在購物車頁面的頂部顯示一條自定義消息,其中包含添加到購物車的第一個產品的分類鏈接。顯示包含第一個產品的分類鏈接的自定義消息添加到購物車
這是消息:
從
{LINK TO CATEGORY OF FIRST PRODUCT ADDED TO CART}
添加更多的T恤,並獲得折扣!
我該如何做到這一點?任何想法?
感謝
這裏是一個自定義函數,將顯示購物車頁面上的自定義消息,與該類別歸檔頁面鏈接的第一個產品添加到購物車。
如果沒有類別的產品被添加到購物車,則不會顯示任何內容。
(可選)您還可以在結帳頁面(取消註釋最後一行)上顯示它。
下面是該代碼:
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文件或也以任何插件文件。
此代碼已經過測試並且功能完整。
參考文獻:
我怎麼也不敢相信好這個作品!非常感謝你! – sebas
爲什麼需要「your_theme_domain」 – sebas
最後一個問題!!如何在購物車內容表下方複製相同的消息? – sebas