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

概要

woocommerce_cart_total フィルタは、WooCommerce のカート内の合計金額を変更する際に使用されるフックです。このフィルタを利用することで、カートの総額(適用される割引、送料などを含む)をカスタマイズしたり、特定の条件に基づいて独自の計算ロジックを実装することができます。

このフィルタは以下のような機能を実装する際によく使われます。

  1. カート合計金額に特定の割引を追加する。
  2. 特定のユーザーグループに対して特別価格を適用する。
  3. 備考欄の情報に基づいて合計金額を変更する。
  4. プロモーションキャンペーンを実施し、カート合計に影響を与える。
  5. 地域に基づく税金の計算をカート合計に反映する。
  6. カートが特定の条件を満たす場合にボーナスを追加する。

構文

add_filter('woocommerce_cart_total', 'my_custom_cart_total', 10, 2);

パラメータ

  • $cart_total (float): カートの合計金額。
  • $cart (WC_Cart): WooCommerceのカートオブジェクト。

戻り値

  • float: 修正後のカートの合計金額。

互換性

  • WooCommerce バージョン: 3.0以上
  • 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: 固定割引を適用

このコードは、カートの合計に対して固定金額(例: 500円)を割引します。

add_filter('woocommerce_cart_total', 'apply_fixed_discount', 10, 2);
function apply_fixed_discount($cart_total, $cart) {
    $fixed_discount = 500;
    return max(0, $cart_total - $fixed_discount);
}

引用元: https://www.example.com

サンプル2: ユーザーグループによる割引

特定のユーザーロールに対して、カート合計を10%割引します。

add_filter('woocommerce_cart_total', 'user_role_discount', 10, 2);
function user_role_discount($cart_total, $cart) {
    if (current_user_can('member')) {
        return $cart_total * 0.9; // 10%オフ
    }
    return $cart_total;
}

引用元: https://www.example.com

サンプル3: 地域に基づく送料を追加

ユーザーの地域に応じた送料をカート合計に追加します。

add_filter('woocommerce_cart_total', 'add_shipping_based_on_region', 10, 2);
function add_shipping_based_on_region($cart_total, $cart) {
    $shipping_cost = (WC()->customer->get_billing_country() === 'JP') ? 300 : 500;
    return $cart_total + $shipping_cost;
}

引用元: https://www.example.com

サンプル4: カスタムプロモーションメッセージの表示

特定のカート合計を条件にしてプロモーションメッセージを表示し、合計を変更します。

add_filter('woocommerce_cart_total', 'custom_promotion_message', 10, 2);
function custom_promotion_message($cart_total, $cart) {
    if ($cart_total > 10000) {
        add_notice('10%オフのプロモーション中です!', 'success');
        return $cart_total * 0.9; // 10%オフ
    }
    return $cart_total;
}

引用元: https://www.example.com

サンプル5: 特定商品へのボーナスを追加

特定の商品のカート合計を増加させるボーナスを追加します。

add_filter('woocommerce_cart_total', 'add_bonus_for_specific_product', 10, 2);
function add_bonus_for_specific_product($cart_total, $cart) {
    foreach ($cart->get_cart() as $cart_item) {
        if ($cart_item['product_id'] === 123) { // 商品ID 123
            return $cart_total + 200; // ボーナス200円を追加
        }
    }
    return $cart_total;
}

引用元: https://www.example.com

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


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