概要
woocommerce_mini_cart_contents
は、WooCommerce のミニカートに表示される商品の内容をフィルタリングするためのフックです。このフィルタを使用すると、カートに追加された商品情報をカスタマイズしたり、特定の条件に基づいて情報を変更したりすることができます。
よく使われる機能
このフィルタは、以下のような機能を実装する際に特によく使われます。
- ミニカートに商品ごとのカスタムデータを表示する。
- 商品の数量や価格を条件に基づいて変化させる。
- エラーメッセージや情報を追加して、ユーザーの体験を改善する。
- 特定の条件に基づき、表示する商品のリストをカスタマイズする。
- カートの内容に基づいて特別なプロモーションを表示する。
- 運送料や割引率をリアルタイムで表示する。
構文
add_filter('woocommerce_mini_cart_contents', 'your_custom_function');
function your_custom_function($cart_contents) {
// ここにカスタマイズを実装
return $cart_contents;
}
パラメータ
$cart_contents
(配列): 現在のカートの内容を表す配列。
戻り値
- (配列): 修正されたカートの内容を返します。
対応バージョン
- WooCommerce: 3.0 以上
- WordPress: 4.0 以上
この関数のアクションでの使用可能性
アクション | 使用可能性 |
---|---|
mu_plugin_loaded | |
registered_post_type | |
plugins_loaded | |
wp_roles_init | |
setup_theme | |
after_setup_theme | |
set_current_user | |
init | |
register_sidebar | |
wp_loaded | |
send_headers | |
parse_query | |
pre_get_posts | |
wp | |
template_redirect | |
get_header | |
wp_head |
サンプルコード
サンプルコード1
add_filter('woocommerce_mini_cart_contents', 'add_custom_data_to_mini_cart');
function add_custom_data_to_mini_cart($cart_contents) {
foreach ($cart_contents as &$item) {
$item['custom_data'] = 'カスタムデータ'; // 商品にカスタムデータを追加
}
return $cart_contents;
}
このサンプルは、ミニカートの各商品の情報に「カスタムデータ」というフィールドを追加するものです。
サンプルコード2
add_filter('woocommerce_mini_cart_contents', 'modify_cart_item_quantity');
function modify_cart_item_quantity($cart_contents) {
foreach ($cart_contents as &$item) {
if ($item['quantity'] > 10) {
$item['quantity'] = 10; // 数量を10に制限
}
}
return $cart_contents;
}
このサンプルは、商品数量が10を超えた場合、その数量を10に制限するものです。
サンプルコード3
add_filter('woocommerce_mini_cart_contents', 'add_discount_message');
function add_discount_message($cart_contents) {
if (WC()->cart->total > 100) {
$cart_contents[] = array('name' => '割引適用', 'value' => '100円以上の購入で10%の割引!');
}
return $cart_contents;
}
このサンプルは、カートの合計金額が100円を超えた場合、割引メッセージをミニカートに追加するものです。
サンプルコード4
add_filter('woocommerce_mini_cart_contents', 'remove_product_from_cart');
function remove_product_from_cart($cart_contents) {
foreach ($cart_contents as $key => $item) {
if ($item['product_id'] == 123) { // 商品IDが123のものを削除
unset($cart_contents[$key]);
}
}
return $cart_contents;
}
このサンプルは、特定の商品の保有IDを元にカートからその商品を削除します。
サンプルコード5
add_filter('woocommerce_mini_cart_contents', 'display_custom_message_on_cart');
function display_custom_message_on_cart($cart_contents) {
if (empty($cart_contents)) {
$cart_contents[] = array('name' => 'お知らせ', 'value' => 'カートは空です!商品を追加してください。');
}
return $cart_contents;
}
このサンプルは、ミニカートが空である場合に「カートは空です!」というお知らせメッセージを表示するものです。