概要
woocommerce_get_related_product_cat_terms
フィルタは、WooCommerceにおける関連商品のカテゴリを取得する際にフックされるフィルタです。これを使用することで、関連商品に表示されるカテゴリをカスタマイズすることができます。このフィルタは、以下のような機能を実装する際によく使われます。
- 関連商品のカテゴリの表示を変更する
- 特定のカテゴリを非表示にする
- カスタムカテゴリを追加する
- 関連商品をより関連性の高いカテゴリにフィルタリングする
- 特定の条件に基づいて関連商品のカテゴリを変更する
- 商品の属性に基づく動的な関連商品のカテゴリの生成
構文
add_filter( 'woocommerce_get_related_product_cat_terms', 'your_function_name', 10, 2 );
パラメータ
$terms
(array): 関連商品のカテゴリ情報を含む配列。$product_id
(int): 商品ID。
戻り値
- (array): フィルタ加工されたカテゴリ情報の配列。
使用可能なバージョン
- WooCommerce: v2.0以降
- WordPress: v4.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_related_product_cat_terms', 'remove_specific_category', 10, 2 );
function remove_specific_category( $terms, $product_id ) {
$terms = array_filter( $terms, function( $term ) {
return $term !== '非表示にしたいカテゴリ';
});
return $terms;
}
このサンプルコードは、特定のカテゴリ(例:「非表示にしたいカテゴリ」)を関連商品のカテゴリリストから除外します。
サンプルコード2: カスタムカテゴリを追加する
add_filter( 'woocommerce_get_related_product_cat_terms', 'add_custom_category', 10, 2 );
function add_custom_category( $terms, $product_id ) {
$terms[] = 'カスタムカテゴリ';
return $terms;
}
このサンプルコードは、関連商品のカテゴリリストに「カスタムカテゴリ」を追加します。
サンプルコード3: 関連商品のカテゴリをフィルタリングする
add_filter( 'woocommerce_get_related_product_cat_terms', 'filter_related_cats', 10, 2 );
function filter_related_cats( $terms, $product_id ) {
return array_intersect( $terms, ['カテゴリ1', 'カテゴリ2'] );
}
このサンプルコードは、関連商品のカテゴリを「カテゴリ1」と「カテゴリ2」のみになるようにフィルタリングします。
サンプルコード4: 特定の条件に基づくカテゴリ変更
add_filter( 'woocommerce_get_related_product_cat_terms', 'conditional_cat_change', 10, 2 );
function conditional_cat_change( $terms, $product_id ) {
if ( has_term( '特定の条件', 'product_cat', $product_id ) ) {
$terms[] = '新しいカテゴリ';
}
return $terms;
}
このサンプルコードは、特定の条件を満たした場合に「新しいカテゴリ」を追加します。
サンプルコード5: カテゴリの表示順を変更
add_filter( 'woocommerce_get_related_product_cat_terms', 'sort_related_cats', 10, 2 );
function sort_related_cats( $terms, $product_id ) {
usort( $terms, function( $a, $b ) {
return $a <=> $b; // アルファベット順
});
return $terms;
}
このサンプルコードは、関連商品のカテゴリの表示順をアルファベット順に変更します。