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

概要

woocommerce_cart_totals_fee_html は、WooCommerce でのカート合計に追加料金を表示する際に使用されるフィルタです。このフィルタを利用することで、追加料金の表示方法やフォーマットをカスタマイズできます。主に以下のような機能を実装する際によく使われます:

  1. 課金項目のラベルやフォーマットの変更
  2. 追加料金の計算方式の変更
  3. 表示する通貨の変更
  4. 追加料金のスタイルやCSSの適用
  5. 追加料金に関するカスタムメッセージの追加
  6. 利用条件に応じた料金の表示・非表示の切替

構文

add_filter('woocommerce_cart_totals_fee_html', 'custom_fee_display', 10, 2);

パラメータ

  • string $fee_html:カート内の追加料金を表すHTML。
  • object $cart_fee:追加料金のオブジェクト(名前や金額などの情報を含む)。

戻り値

  • string:フィルタされた追加料金のHTML。

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

  • 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_totals_fee_html', 'custom_discount_fee_html', 10, 2);

function custom_discount_fee_html($fee_html, $cart_fee) {
    if ($cart_fee->name === 'ディスカウント') {
        return '<strong>特別割引:</strong> ' . wc_price($cart_fee->amount);
    }
    return $fee_html;
}

このコードは、カート内に「ディスカウント」と呼ばれる追加料金がある場合、その表示を「特別割引」としてカスタマイズします。

サンプルコード 2

add_filter('woocommerce_cart_totals_fee_html', 'custom_tax_fee_display', 10, 2);

function custom_tax_fee_display($fee_html, $cart_fee) {
    if ($cart_fee->name === '税金') {
        return '<div class="custom-tax">税金合計: ' . $fee_html . '</div>';
    }
    return $fee_html;
}

ここでは、税金が表示される場合、そのHTMLをカスタムクラス付きの

<

div>でラップしています。

サンプルコード 3

add_filter('woocommerce_cart_totals_fee_html', 'change_fee_label', 10, 2);

function change_fee_label($fee_html, $cart_fee) {
    return str_replace('送料', '配送費用', $fee_html);
}

このコードは、追加料金が「送料」として表示される場合に、そのラベルを「配送費用」に変更します。

サンプルコード 4

add_filter('woocommerce_cart_totals_fee_html', 'add_fee_custom_message', 10, 2);

function add_fee_custom_message($fee_html, $cart_fee) {
    return $fee_html . '<br><small>特別サービス料金が適用されます。</small>';
}

このサンプルでは、追加料金の下に特別サービスに関するメッセージを追加しています。

サンプルコード 5

add_filter('woocommerce_cart_totals_fee_html', 'currency_symbol_customization', 10, 2);

function currency_symbol_customization($fee_html, $cart_fee) {
    $new_fee_html = str_replace('¥', 'JP¥', $fee_html);
    return $new_fee_html;
}

このコードは、追加料金の表示時に通貨シンボルを「¥」から「JP¥」に変更します。

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


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