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

概要

woocommerce_cart_product_subtotal フィルタは、WooCommerce のカートにおいて、商品の小計を表示する際に使用されるフィルタです。このフィルタを使うことで、商品の小計の表示内容をカスタマイズすることができます。例えば、通貨記号の変更、表示フォーマットの調整、特定の条件に基づく価格変更などが可能です。一般的に、このフィルタは次のような機能を実装する際に頻繁に使用されます。

  1. 小計の通貨記号を変更する。
  2. 割引価格を強調表示する。
  3. 税額を含めた小計の表示形式を変更する。
  4. 特定のプロモーションの有効な場合に祝福メッセージを表示する。
  5. UIのために小計のスタイルを調整する。
  6. 対応する条件に基づいてカスタムフォーマットで小計を表示する。

構文

add_filter( 'woocommerce_cart_product_subtotal', 'your_function_name', 10, 3 );

パラメータ

  • $product_subtotal (string) – 商品の小計表示
  • $cart_item (array) – 現在処理中のカートアイテム
  • $cart_item_key (string) – 現在のカートアイテムのキー

戻り値

  • フィルタされた小計(string)

バージョン情報

  • WooCommerceのバージョン: 2.1 以降で使用可能
  • 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_cart_product_subtotal', 'change_currency_symbol', 10, 3 );

function change_currency_symbol( $product_subtotal, $cart_item, $cart_item_key ) {
    return str_replace( '¥', '$', $product_subtotal );
}

このサンプルコードは、カートの商品小計の通貨記号を日本円の「¥」からアメリカドルの「$」に変更します。

サンプルコード2 – 割引価格の表示を強調

add_filter( 'woocommerce_cart_product_subtotal', 'highlight_discount_price', 10, 3 );

function highlight_discount_price( $product_subtotal, $cart_item, $cart_item_key ) {
    if ( isset( $cart_item['data'] ) && $cart_item['data']->get_sale_price() ) {
        return '<span style="color:red;">' . $product_subtotal . '</span>';
    }
    return $product_subtotal;
}

このサンプルは、割引が適用されている商品の小計を赤色に変更し、目立たせます。

サンプルコード3 – 小計の税額を含めて表示

add_filter( 'woocommerce_cart_product_subtotal', 'include_tax_in_subtotal', 10, 3 );

function include_tax_in_subtotal( $product_subtotal, $cart_item, $cart_item_key ) {
    $tax = isset( $cart_item['data'] ) ? $cart_item['data']->get_price_including_tax() : 0;
    return $product_subtotal . ' (税金含む: ' . wc_price( $tax ) . ')';
}

このコードでは、商品の小計表示に税金を含めた金額を追加入力しています。税金が含まれていることが明確になります。

サンプルコード4 – カスタム条件による表示

add_filter( 'woocommerce_cart_product_subtotal', 'custom_condition_subtotal', 10, 3 );

function custom_condition_subtotal( $product_subtotal, $cart_item, $cart_item_key ) {
    if ( wp_is_mobile() ) {
        return 'モバイル専用価格: ' . $product_subtotal;
    }
    return $product_subtotal;
}

このサンプルでは、移動端末(モバイルデバイス)の場合のみ、カスタムメッセージを付加して小計を表示します。

サンプルコード5 – CSSでスタイルを変更

add_filter( 'woocommerce_cart_product_subtotal', 'styled_cart_subtotal', 10, 3 );

function styled_cart_subtotal( $product_subtotal, $cart_item, $cart_item_key ) {
    return '<div class="cart-subtotal">' . $product_subtotal . '</div>';
}

このコードは、カートの商品小計を <div class="cart-subtotal"> タグでラップし、特定のCSSスタイルを適用できるようにします。

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


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