プラグインWooCommerceのwoocommerce_add_to_cart_item_name_in_quotesフィルタの使用方法・解説

概要

woocommerce_add_to_cart_item_name_in_quotesフィルタは、WooCommerceで商品をカートに追加した際に表示される商品の名前をカスタマイズするために使用されるフックです。このフィルタを使うことで、以下のような機能を実装する際によく利用されます。

  1. 商品名を特定のフォーマットで表示する
  2. 商品に特定のHTMLタグを追加する
  3. 特定のテキストを商品名の前後に追加する
  4. 商品名のスタイルを変更する
  5. 商品名に特定のクラスを追加する
  6. 商品名を他の情報と組み合わせて表示する

構文

apply_filters( 'woocommerce_add_to_cart_item_name_in_quotes', $product_name, $cart_item, $cart_item_key );

パラメータ

  • $product_name:商品名の文字列
  • $cart_item:カートアイテムの配列
  • $cart_item_key:カートアイテムの一意のキー

戻り値

フィルタにより変更された商品名の文字列

対応するWooCommerceのバージョン

WooCommerce 3.0以降

対応するWordPressのバージョン

WordPress 4.0以降

サンプルコード

サンプルコード1: 商品名を大文字で表示する

add_filter( 'woocommerce_add_to_cart_item_name_in_quotes', 'uppercase_product_name', 10, 3 );

function uppercase_product_name( $product_name, $cart_item, $cart_item_key ) {
    return strtoupper( $product_name );
}

このサンプルコードは、カートに追加された商品の名前を大文字で表示します。

サンプルコード2: 商品名の前に特定のテキストを追加する

add_filter( 'woocommerce_add_to_cart_item_name_in_quotes', 'prepend_custom_text_to_product_name', 10, 3 );

function prepend_custom_text_to_product_name( $product_name, $cart_item, $cart_item_key ) {
    return '特別: ' . $product_name;
}

このサンプルコードでは、商品の名前の前に「特別: 」というテキストを追加しています。

サンプルコード3: 商品名をHTMLタグで囲む

add_filter( 'woocommerce_add_to_cart_item_name_in_quotes', 'wrap_product_name_in_html', 10, 3 );

function wrap_product_name_in_html( $product_name, $cart_item, $cart_item_key ) {
    return '<strong>' . $product_name . '</strong>';
}

このサンプルコードは、商品の名前を<strong>タグで囲むことで、太字で表示します。

サンプルコード4: 商品名にカスタムクラスを追加する

add_filter( 'woocommerce_add_to_cart_item_name_in_quotes', 'add_class_to_product_name', 10, 3 );

function add_class_to_product_name( $product_name, $cart_item, $cart_item_key ) {
    return '<span class="custom-class">' . $product_name . '</span>';
}

このサンプルコードは、商品の名前にカスタムクラスを持つ<span>タグを追加します。

サンプルコード5: 商品名を変数でラップする

add_filter( 'woocommerce_add_to_cart_item_name_in_quotes', 'wrap_product_name_in_variable', 10, 3 );

function wrap_product_name_in_variable( $product_name, $cart_item, $cart_item_key ) {
    $custom_variable = '商品名: ';
    return $custom_variable . $product_name;
}

このサンプルコードは、商品の名前の前に「商品名: 」という変数を追加します。

この関数のアクションでの使用可能性

アクション 使用可能性
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

このフィルタは、主に商品の表示に関わるところで活用されるため、上記のアクションでの使用がないことが多いです。

この関数について質問する


上の計算式の答えを入力してください