概要
woocommerce_cart_item_visible
フィルタは、WooCommerceにおいてカート内の商品が表示されるかどうかを制御するために使用されるフックです。このフィルタを利用することで、商品がカート内にある場合にその商品の可視性を変更したり、特定の条件に基づいて商品を非表示にすることが可能です。特に、以下のようなケースでよく使われます:
- 特定のユーザーグループに対して商品の可視性を制御する場合
- 特定のプロモーションにより商品を非表示にする場合
- 在庫がない商品をカートから非表示にする場合
- カート内の特定のアイテムが特定の条件を満たさないときに非表示にする場合
- 顧客の地域に基づいて特定の商品を表示または非表示にする場合
- テスト目的でカート内の商品を一時的に非表示にする場合
構文
add_filter( 'woocommerce_cart_item_visible', 'カスタム関数名', 10, 3 );
パラメータ
$visible
(boolean): 商品が表示されるかどうかを示すフラグ。$cart_item
(array): カート内の商品の情報を含む配列。$cart_item_key
(string): 商品のカート内キー。
戻り値
- (boolean): 商品が表示される場合は
true
、非表示の場合はfalse
を返す。
使用可能なプラグインおよびバージョン
- 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_cart_item_visible', 'hide_product_for_specific_user', 10, 3 );
function hide_product_for_specific_user( $visible, $cart_item, $cart_item_key ) {
if ( is_user_logged_in() && current_user_can('subscriber') ) {
return false; // サブスクライバーには商品を非表示にする
}
return $visible;
}
このサンプルは、ログインしているユーザーがサブスクライバーである場合、カート内の商品を非表示にします。
サンプルコード 2: 在庫切れの商品を非表示にする
add_filter( 'woocommerce_cart_item_visible', 'hide_out_of_stock_products', 10, 3 );
function hide_out_of_stock_products( $visible, $cart_item, $cart_item_key ) {
$product = $cart_item['data'];
if ( ! $product->is_in_stock() ) {
return false; // 在庫切れの商品を非表示
}
return $visible;
}
このサンプルは、カート内に在庫がない商品を非表示にします。
サンプルコード 3: 特定のプロモーションに応じて商品を非表示にする
add_filter( 'woocommerce_cart_item_visible', 'hide_product_on_promotion', 10, 3 );
function hide_product_on_promotion( $visible, $cart_item, $cart_item_key ) {
if ( isset( $_GET['promo'] ) && $_GET['promo'] === 'no_display' ) {
return false; // プロモーションが適用されている場合、商品を非表示
}
return $visible;
}
このサンプルは、URLパラメータにプロモーションが含まれている場合、カート内の商品を非表示にします。
サンプルコード 4: 地域に基づいて商品を非表示にする
add_filter( 'woocommerce_cart_item_visible', 'hide_product_based_on_location', 10, 3 );
function hide_product_based_on_location( $visible, $cart_item, $cart_item_key ) {
if ( WC()->customer->get_shipping_country() === 'JP' ) {
return false; // 日本からの顧客には商品を非表示
}
return $visible;
}
このサンプルは、顧客の配送先が日本の場合、カート内の商品を非表示にします。
サンプルコード 5: テスト目的で商品を一時的に非表示にする
add_filter( 'woocommerce_cart_item_visible', 'hide_product_for_testing', 10, 3 );
function hide_product_for_testing( $visible, $cart_item, $cart_item_key ) {
// テスト中として、すべての商品を非表示にする
return false;
}
このサンプルは、テスト中の期間中にすべてのカート内商品を非表示にします。