概要
woocommerce_product_variation_title
フィルタは、WooCommerceの特定の商品のバリエーションタイトルを変更するために使用されます。このフィルタを使うことで、カスタムのタイトルを設定したり、表示を変更したりすることができます。このフィルタは、様々な自動生成されたタイトルやバリエーション名のフォーマットをカスタマイズしたい場合に非常に便利です。よく使われる機能としては、以下のようなものがあります。
- バリエーションの属性名を強調表示する
- 特定の商品情報をタイトルに追加する
- 外部販売者の情報をタイトルに組み込む
- 特定の条件に基づいてタイトルを変更する
- 商品バリエーションの説明を短縮する
- デフォルトのタイトルにプレフィックスやサフィックスを追加する
構文
add_filter('woocommerce_product_variation_title', 'custom_variation_title', 10, 2);
パラメータ
string $title
– 現在のタイトルWC_Product_Variation $variation
– バリエーションオブジェクト
戻り値
string
– 変更されたタイトル
使用可能なバージョン
- WooCommerce: 2.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_product_variation_title', 'add_attribute_name_to_variation_title', 10, 2);
function add_attribute_name_to_variation_title($title, $variation) {
$attribute_name = 'サイズ: ';
return $attribute_name . $title;
}
[source: WooCommerce documentation]
サンプル 2: 特定のバリエーションを強調表示する
特定のバリエーション(例: “赤”)が選択されている場合、そのバリエーションのタイトルに挿入されるテキストを変更します。
add_filter('woocommerce_product_variation_title', 'highlight_red_variation', 10, 2);
function highlight_red_variation($title, $variation) {
if ($variation->get_attribute('color') === '赤') {
return '★ ' . $title . ' ★';
}
return $title;
}
[source: WooCommerce tutorials]
サンプル 3: ユーザーによるカスタマイズを実装する
ユーザーが管理画面から設定したカスタムプレフィックスをタイトルに追加する例です。
add_filter('woocommerce_product_variation_title', 'add_user_custom_prefix', 10, 2);
function add_user_custom_prefix($title, $variation) {
$prefix = get_option('custom_variation_prefix', '特別版: ');
return $prefix . $title;
}
[source: Custom theme development article]
サンプル 4: バリエーションの簡略化
このコードは、タイトルの長さを制限し、簡潔な表現にします。
add_filter('woocommerce_product_variation_title', 'shorten_variation_title', 10, 2);
function shorten_variation_title($title, $variation) {
return wp_trim_words($title, 4, '...');
}
[source: WordPress best practices]
サンプル 5: プレフィックスを条件付きで設定
バリエーションが特定の条件を満たす場合にのみ、カスタムプレフィックスを追加します。
add_filter('woocommerce_product_variation_title', 'conditional_prefix_variation_title', 10, 2);
function conditional_prefix_variation_title($title, $variation) {
$condition = $variation->get_stock_status();
if ($condition === 'outofstock') {
return '売り切れ: ' . $title;
}
return $title;
}
[source: WooCommerce hooks guide]