はアーカイブのページがカートに追加された最初の製品のリンクカテゴリで、カートのページにカスタムメッセージを表示するカスタム関数です。
カテゴリのない製品がカートに追加された場合、何も表示されません。
オプションで、チェックアウトページ(最後の行のコメントを外して)に表示することもできます。ここで
は、このコードです:
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
なぜ「あなたの_ドメイン_」の必要性 – sebas
最後の質問!カート内容テーブルのすぐ下に同じメッセージを複製するにはどうすればいいですか? – sebas