概要
woocommerce_order_item_visible
フィルタは、WooCommerceでの注文アイテムの表示制御に使用されるフックです。このフィルタを使用することで、特定の条件に基づいて注文のアイテムが表示されるかどうかを制御できます。以下のような機能を実装する際によく使われます。
- 特定のユーザーグループに対するアイテムの表示・非表示の切り替え
- プロモーションやキャンペーンに応じたアイテムの表示
- 購入した商品に対するカスタムメッセージの表示
- 在庫切れ商品や非販売商品を非表示にする
- アイテムに関連するカスタムフィールドの表示・非表示
- セキュリティやプライバシーの理由によるアイテムの制御
構文
add_filter('woocommerce_order_item_visible', 'your_custom_function', 10, 3);
パラメータ
$visible
(bool): アイテムが表示されるかどうかのフラグ。$item_id
(int): アイテムのID。$order
(WC_Order): 注文オブジェクト。
戻り値
- bool: アイテムが表示される場合は
true
、非表示の場合はfalse
を返します。
使用可能なバージョン
- WooCommerce バージョン: 3.0以上推奨
- WordPress バージョン: 4.7以上推奨
サンプルコード
サンプルコード1: 特定のユーザーに対するアイテムの非表示
add_filter('woocommerce_order_item_visible', 'hide_order_item_for_user', 10, 3);
function hide_order_item_for_user($visible, $item_id, $order) {
if (current_user_can('subscriber')) {
return false; // サブスクリバーユーザーにはアイテムを非表示
}
return $visible;
}
このコードは、サブスクリバーユーザーに対して、注文アイテムを非表示にするものです。
サンプルコード2: 在庫切れ商品の非表示
add_filter('woocommerce_order_item_visible', 'hide_out_of_stock_items', 10, 3);
function hide_out_of_stock_items($visible, $item_id, $order) {
$product = $order->get_product($item_id);
if ($product && !$product->is_in_stock()) {
return false; // 在庫切れ商品は非表示
}
return $visible;
}
このコードは、在庫切れの商品を注文表示から非表示にする機能を実装しています。
サンプルコード3: セール対象商品を特別に表示
add_filter('woocommerce_order_item_visible', 'highlight_sale_items', 10, 3);
function highlight_sale_items($visible, $item_id, $order) {
$product = $order->get_product($item_id);
if ($product && $product->is_on_sale()) {
// セール商品は常に表示
return true;
}
return $visible;
}
このコードは、セール中の商品は必ず表示されるように設定しています。
サンプルコード4: 特定のカテゴリーの商品を非表示
add_filter('woocommerce_order_item_visible', 'hide_items_from_category', 10, 3);
function hide_items_from_category($visible, $item_id, $order) {
$product = $order->get_product($item_id);
if ($product && has_term('restricted', 'product_cat', $product->get_id())) {
return false; // 'restricted' カテゴリーの商品は非表示
}
return $visible;
}
このコードでは、特定のカテゴリーに属する商品を非表示にしています。
サンプルコード5: カスタムメッセージの表示
add_filter('woocommerce_order_item_visible', 'custom_message_for_items', 10, 3);
function custom_message_for_items($visible, $item_id, $order) {
if ($item_id == 123) { // 特定のアイテムIDの場合
echo "<p>特別なメッセージ: このアイテムは特別です!</p>";
}
return $visible;
}
このコードは、特定のアイテムIDに対してカスタムメッセージを表示するためのものです。
この関数のアクションでの使用可能性
アクション | 使用可能 |
---|---|
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 |
この表は、woocommerce_order_item_visible
フィルタがどのアクションで使用可能かを示しています。