概要
woocommerce_get_product_terms
フィルタは、WooCommerceの商品に関連するターム(カテゴリーやタグなど)を取得する際に使用されます。このフィルタは、特定の商品IDに基づき、関連付けられたタームをカスタマイズするためによく利用されます。以下はこのフィルタを用いる一般的な機能の例です。
- 商品タームの表示順を変更
- タームの表示内容をカスタマイズ
- 特定のタームを除外
- タームを新たに追加
- 商品の分類を動的に変更
- カスタムフィールドに基づくタームフィルタリング
構文
add_filter( 'woocommerce_get_product_terms', 'custom_function_name', 10, 3 );
パラメータ
$terms
– 現在のタームの配列$product_id
– 商品のID$taxonomy
– タクソノミー名(例: category, tag)
戻り値
フィルタが適用された後のタームの配列。
使用可能なプラグインのバージョン
- WooCommerce: 3.0.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_get_product_terms', 'custom_order_product_terms', 10, 3 );
function custom_order_product_terms( $terms, $product_id, $taxonomy ) {
if ( 'product_cat' === $taxonomy ) {
usort( $terms, function( $a, $b ) {
return strcmp( $a->name, $b->name );
});
}
return $terms;
}
このサンプルコードは、商品カテゴリーのタームをアルファベット順に並べ替える処理を実装しています。
サンプルコード2: 特定のタームを除外
add_filter( 'woocommerce_get_product_terms', 'exclude_specific_product_terms', 10, 3 );
function exclude_specific_product_terms( $terms, $product_id, $taxonomy ) {
if ( 'product_tag' === $taxonomy ) {
$terms = array_filter( $terms, function( $term ) {
return $term->slug !== 'unwanted-tag';
});
}
return $terms;
}
このサンプルコードは、特定のタグを除外して他のタグを取得するためのフィルタを適用します。
サンプルコード3: カスタムタームの追加
add_filter( 'woocommerce_get_product_terms', 'add_custom_product_term', 10, 3 );
function add_custom_product_term( $terms, $product_id, $taxonomy ) {
if ( 'product_cat' === $taxonomy ) {
$terms[] = get_term_by( 'slug', 'new-category', 'product_cat' );
}
return $terms;
}
このサンプルコードは、特定の商品カテゴリー(カスタム)を既存のタームに追加するものです。
サンプルコード4: カスタムフィールドに基づくタームフィルタリング
add_filter( 'woocommerce_get_product_terms', 'filter_product_terms_by_custom_field', 10, 3 );
function filter_product_terms_by_custom_field( $terms, $product_id, $taxonomy ) {
if ( 'product_cat' === $taxonomy ) {
$custom_field_value = get_post_meta( $product_id, '_custom_field_key', true );
if ( $custom_field_value ) {
// Custom filtering logic here
}
}
return $terms;
}
このサンプルコードは、カスタムフィールドの値に基づいてタームをフィルタリングするための基本的な構造を示しています。
サンプルコード5: タームの表示内容をカスタマイズ
add_filter( 'woocommerce_get_product_terms', 'customize_term_display', 10, 3 );
function customize_term_display( $terms, $product_id, $taxonomy ) {
foreach ( $terms as $term ) {
$term->name = strtoupper( $term->name ); // ターム名を大文字に変更
}
return $terms;
}
このサンプルコードは、ターム名をすべて大文字に変換することで、表示内容をカスタマイズします。
これらのサンプルコードは、WooCommerceのwoocommerce_get_product_terms
フィルタの使用方法を示しており、それぞれ異なる目的に対応しています。