概要
woocommerce_product_title
フィルタは、WooCommerceにおいて商品のタイトルを変更するために使用されるフックです。このフィルタは、商品ページや商品一覧で表示される商品のタイトルをカスタマイズする際に役立ちます。具体的には、以下のような機能を実装する際によく使われます。
- 商品タイトルに特定のプレフィックスまたはサフィックスを追加する。
- タイトルの一部を翻訳またはローカライズする。
- タイトルのスタイルを変更するためにHTMLタグを追加する。
- タイトルが特定の条件に基づいて異なる形式で表示されるようにする。
- 商品の在庫状況に応じてタイトルを変更する。
- 特定のカスタムフィールドの値を基にタイトルを更新する。
構文
add_filter('woocommerce_product_title', 'function_name', 10, 2);
パラメータ
$title
(string): 現在の商品のタイトル。$product
(WC_Product): WooCommerceの製品オブジェクト。
戻り値
- (string): 変更またはそのままの商品のタイトル。
使用可能なプラグインWooCommerceのバージョン
WooCommerce 2.1以降で利用可能。
ワードプレスのバージョン
WordPress 4.0以降で動作。
サンプルコード
サンプルコード 1: 行頭に特定の文字列を追加
このコードは、すべての商品のタイトルの前に「新商品: 」というプレフィックスを追加します。
add_filter('woocommerce_product_title', 'add_prefix_to_product_title', 10, 2);
function add_prefix_to_product_title($title, $product) {
return '新商品: ' . $title;
}
引用元: https://docs.woocommerce.com/
サンプルコード 2: 在庫あり商品のタイトルを強調表示
在庫がある商品のタイトルを太字で表示するコードです。
add_filter('woocommerce_product_title', 'highlight_in_stock_product_title', 10, 2);
function highlight_in_stock_product_title($title, $product) {
if ($product->is_in_stock()) {
return '<strong>' . $title . '</strong>';
}
return $title;
}
引用元: https://woocommerce.com/
サンプルコード 3: 特定のカスタムフィールドを使ったタイトルの変更
このコードは、商品に関連する特定のカスタムフィールドの値をタイトルに追加します。
add_filter('woocommerce_product_title', 'append_custom_field_to_title', 10, 2);
function append_custom_field_to_title($title, $product) {
$custom_field_value = get_post_meta($product->get_id(), 'custom_field_key', true);
return $title . ' - ' . $custom_field_value;
}
引用元: https://developer.wordpress.org/
サンプルコード 4: タイトルの長さを制限
商品タイトルの長さを50文字に制限し、オーバーした場合は”…”を追加します。
add_filter('woocommerce_product_title', 'limit_product_title_length', 10, 2);
function limit_product_title_length($title, $product) {
return (strlen($title) > 50) ? substr($title, 0, 50) . '...' : $title;
}
引用元: https://wordpress.org/
サンプルコード 5: 特定のカテゴリーの商品タイトルを変更
特定のカテゴリーの商品の場合にタイトルをカスタマイズするコードです。
add_filter('woocommerce_product_title', 'modify_title_for_specific_category', 10, 2);
function modify_title_for_specific_category($title, $product) {
if (has_term('特定のカテゴリー', 'product_cat', $product->get_id())) {
return '特別: ' . $title;
}
return $title;
}
引用元: https://woocommerce.com/
この関数のアクションでの使用可能性
アクション | 使用例 |
---|---|
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 |