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

概要

wc_add_to_cart_message_html フィルタは、WooCommerce 商品がカートに追加された際に表示されるメッセージのHTMLをカスタマイズするためのフィルタです。これを使用することで、カート追加メッセージにカスタムテキストやスタイルを追加したり、特定の条件に合わせた表示を実現することができます。このフィルタは、WooCommerce の様々な機能やデザインを個別のニーズに合わせて変更する際に非常に便利です。

よく使われる機能は以下の通りです:

  1. カート追加メッセージのデザイン変更
  2. 複数商品追加時のメッセージの統合
  3. 特定の商品に基づくカスタムメッセージの表示
  4. メッセージのトーンやスタイルの変更
  5. 購入促進のための特別オファーの表示
  6. 商品の関連情報(例:在庫情報)の追加表示

構文

add_filter( 'wc_add_to_cart_message_html', 'custom_function_name', 10, 2 );

パラメータ

  • $message: 変更前のカート追加メッセージのHTML。
  • $product_id: 追加された商品のID。

戻り値

  • 変更後のカート追加メッセージのHTML。

バージョン

  • WooCommerce バージョン: 3.0+
  • WordPress バージョン: 4.0+

サンプルコード

サンプルコード1: 基本的なメッセージの変更

add_filter( 'wc_add_to_cart_message_html', 'custom_add_to_cart_message', 10, 2 );
function custom_add_to_cart_message( $message, $product_id ) {
    return '<div class="custom-message">商品をカートに追加しました!</div>';
}

このコードは、カートに商品を追加した時に表示されるメッセージをカスタムHTMLで変更します。

サンプルコード2: 特定の商品に対するメッセージのカスタマイズ

add_filter( 'wc_add_to_cart_message_html', 'custom_message_for_specific_product', 10, 2 );
function custom_message_for_specific_product( $message, $product_id ) {
    if ( $product_id == 123 ) { // 商品IDが123の場合
        return '特別オファー!商品をカートに追加しました。';
    }
    return $message;
}

このコードは、特定の商品(商品IDが123)の場合に、別のメッセージを表示します。

サンプルコード3: 商品数に応じたメッセージ変更

add_filter( 'wc_add_to_cart_message_html', 'custom_message_for_multiple_products', 10, 2 );
function custom_message_for_multiple_products( $message, $product_id ) {
    if ( WC()->cart->cart_contents_count > 1 ) {
        return 'カートに複数の商品があります!';
    }
    return $message;
}

このコードは、カート内に複数の商品がある場合にカスタムメッセージを表示します。

サンプルコード4: メッセージに在庫情報を追加

add_filter( 'wc_add_to_cart_message_html', 'add_stock_info_to_message', 10, 2 );
function add_stock_info_to_message( $message, $product_id ) {
    $product = wc_get_product( $product_id );
    $stock_status = $product->get_stock_status() === 'instock' ? '在庫あり' : '在庫切れ';
    return $message . '<br>' . $stock_status;
}

このコードは、カート追加メッセージに在庫状況を追加します。

サンプルコード5: スタイルを強調表示するメッセージ

add_filter( 'wc_add_to_cart_message_html', 'highlight_add_to_cart_message', 10, 2 );
function highlight_add_to_cart_message( $message, $product_id ) {
    return '<strong style="color: red;">' . $message . '</strong>';
}

このコードは、カート追加メッセージを赤色の強調体で表示します。

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

アクション 使用例
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

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


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