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

概要

woocommerce_cart_subtotal フィルタは、WooCommerce のカート内小計をカスタマイズするために使用されます。このフィルタは、カートの小計を表示したい場面や、金額を形式化したり、特定の条件に応じて変更したい場合に役立ちます。主に以下のような機能を実装する際によく使われます:

  1. カートの小計にカスタムクーポンやディスカウントを適用する
  2. 特定の製品に対して異なる計算方法を適用する
  3. 通貨記号やフォーマットを変更する
  4. ローカライズされた金額表示を実現する
  5. 小計に税金や手数料を含める
  6. カートの小計を表示する際にカスタムHTMLを追加する

構文

apply_filters( 'woocommerce_cart_subtotal', $cart_subtotal, $compound, $cart );

パラメータ

  • $cart_subtotal (string) – カート内小計の文字列。
  • $compound (bool) – 複合小計であるかどうかのフラグ。
  • $cart (WC_Cart) – 使用中のカートオブジェクト。

戻り値

  • フィルタ後のカート内小計 (string)。

使用可能なプラグインバージョン

  • WooCommerce 2.0以降

使用可能な WordPress バージョン

  • 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_subtotal', 'custom_cart_subtotal_discount', 10, 3);
function custom_cart_subtotal_discount($cart_subtotal, $compound, $cart) {
    $discount = 10; // 固定の割引額
    return wc_price(wc_get_price_including_tax($cart) - $discount);
}

このコードは、カートの小計から一定の割引を適用するためのサンプルです。

サンプル 2: カート小計の通貨フォーマット変更

add_filter('woocommerce_cart_subtotal', 'custom_cart_subtotal_currency', 10, 3);
function custom_cart_subtotal_currency($cart_subtotal, $compound, $cart) {
    return '¥' . $cart_subtotal; // 通貨記号を変更
}

このコードは小計の表示形式を‘¥’で始めるようにカスタマイズしています。

サンプル 3: 税金を含む小計の表示

add_filter('woocommerce_cart_subtotal', 'include_tax_in_cart_subtotal', 10, 3);
function include_tax_in_cart_subtotal($cart_subtotal, $compound, $cart) {
    if ($cart->is_empty()) {
        return $cart_subtotal; 
    }
    return $cart_subtotal . ' (税抜)'; // 税金情報を表示
}

このコードは、税金を含む形でカート小計を表示するサンプルです。

サンプル 4: カート小計の前にカスタムテキストを追加

add_filter('woocommerce_cart_subtotal', 'prepend_text_to_cart_subtotal', 10, 3);
function prepend_text_to_cart_subtotal($cart_subtotal, $compound, $cart) {
    return '現在の小計: ' . $cart_subtotal; // カスタムテキストを追加
}

このコードは、カートの小計の前にテキストを追加する方法を示しています。

サンプル 5: 小計の表示スタイルの変更

add_filter('woocommerce_cart_subtotal', 'style_cart_subtotal', 10, 3);
function style_cart_subtotal($cart_subtotal, $compound, $cart) {
    return '<span style="color: red; font-weight: bold;">' . $cart_subtotal . '</span>'; // スタイルを適用
}

このコードは、カート小計の表示スタイルを変更するためのサンプルです。

各サンプルコードはWooCommerceのフィルタを使った異なる利用方法を示しています。

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


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