概要
woocommerce_get_children
フィルタは、WooCommerce における製品やカテゴリの子アイテムを取得する際のフックです。このフィルタは主に以下のような機能を実装する際に役立ちます。
- 子製品のリストをカスタマイズ
- 特定の条件に基づいた子製品のフィルタリング
- 子製品の表示順を変更
- 子製品にメタデータを追加
- 条件付きロジックによる特定の子製品の非表示
- クエリパラメータの操作
構文
add_filter('woocommerce_get_children', 'your_function_name', 10, 2);
パラメータ
$children
(array): フィルタリングされる子アイテムの配列$parent_id
(int): 親アイテムのID
戻り値
- array: フィルタリング後の子アイテムの配列
使用可能なプラグインのバージョン
- WooCommerce: 5.0 以降
- WordPress: 5.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_get_children', function($children, $parent_id) {
$filtered_children = array();
foreach ($children as $child) {
if (get_post_meta($child, 'featured_product', true)) {
$filtered_children[] = $child;
}
}
return $filtered_children;
}, 10, 2);
引用元: https://woocommerce.github.io/code-reference/classes/WC-Product-simple.html
サンプルコード2: 子製品の表示順を変更
このサンプルコードは、子製品の表示順をランダムに変更します。
add_filter('woocommerce_get_children', function($children, $parent_id) {
shuffle($children);
return $children;
}, 10, 2);
引用元: https://developer.wordpress.org/reference/functions/shuffle/
サンプルコード3: 特定の子製品を非表示にする
このサンプルコードでは、特定のIDを持つ子製品をリストから除外します。
add_filter('woocommerce_get_children', function($children, $parent_id) {
$exclude_ids = array(12, 34);
return array_diff($children, $exclude_ids);
}, 10, 2);
引用元: https://developer.wordpress.org/reference/functions/array_diff/
サンプルコード4: 子製品にメタデータを追加
このサンプルコードでは、子製品にカスタムメタデータを追加します。
add_filter('woocommerce_get_children', function($children, $parent_id) {
foreach ($children as $child) {
update_post_meta($child, 'custom_meta_key', 'value');
}
return $children;
}, 10, 2);
引用元: https://developer.wordpress.org/reference/functions/update_post_meta/
サンプルコード5: クエリパラメータの操作
このサンプルコードは、任意のクエリパラメータを基に子製品をフィルタリングします。
add_filter('woocommerce_get_children', function($children, $parent_id) {
if (isset($_GET['filter_on'])) {
return array_filter($children, function($child) {
return get_post_meta($child, 'filter_key', true) == 'filter_value';
});
}
return $children;
}, 10, 2);
引用元: https://developer.wordpress.org/reference/functions/array_filter/