プラグインWooCommerceのwoocommerce_cart_calculate_feesアクションの使用方法・解説

概要

woocommerce_cart_calculate_feesは、WooCommerceにおいてカートの合計金額に手数料を追加するためのフックです。このアクションは、カート内の商品や最終的な支払い金額に影響を与える要素をカスタマイズする際によく使われます。具体的には、以下のような機能実装に利用されることが一般的です。

  1. カスタム手数料の追加(例:サービス料、配送手数料など)
  2. プロモーションやキャンペーンの適用(例:特定の条件を満たした際の割引)
  3. 特定ユーザーグループへの特別価格を適用する機能
  4. 複数の通貨による価格調整
  5. 顧客のロケーションに基づく税金の計算
  6. 特定の製品カテゴリに応じた追加費用の設定

構文

add_action( 'woocommerce_cart_calculate_fees', 'your_function_name' );

パラメータ

  • WC_Cart $cart:カートオブジェクト。カート内のアイテムや合計金額を管理します。

戻り値

  • このアクション自体は値を戻しませんが、woocommerce_calculate_feesアクションによってカート料金が調整されます。

WooCommerceのバージョン

  • これはWooCommerce 2.0以降のバージョンで使用可能です。

WordPressのバージョン

  • WooCommerceプラグインが動作する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_action( 'woocommerce_cart_calculate_fees', 'add_custom_service_fee' );
function add_custom_service_fee() {
    global $woocommerce;
    $service_fee = 5; // 固定のサービス料
    $woocommerce->cart->add_fee( 'サービス料', $service_fee );
}

このサンプルコードは、カートに固定のサービス料を追加します。サービス料は常に5ドルで設定されています。

サンプルコード2

add_action( 'woocommerce_cart_calculate_fees', 'apply_discount_based_on_product_quantity' );
function apply_discount_based_on_product_quantity() {
    global $woocommerce;
    $cart_total_quantity = $woocommerce->cart->get_cart_contents_count();
    if ( $cart_total_quantity > 5 ) {
        $discount = 10; // 数量が6以上の場合の割引額
        $woocommerce->cart->add_fee( '数量割引', -$discount );
    }
}

このサンプルコードは、カート内の商品の数量が6以上の場合に10ドルの割引を適用します。

サンプルコード3

add_action( 'woocommerce_cart_calculate_fees', 'add_location_based_tax' );
function add_location_based_tax() {
    global $woocommerce;
    $customer_country = $woocommerce->customer->get_shipping_country();
    if ( $customer_country == 'JP' ) {
        $tax = 8;  // 日本の税率
        $woocommerce->cart->add_fee( '消費税', $tax );
    }
}

このサンプルコードは、顧客の配送先が日本の場合に8ドルの消費税を追加します。

サンプルコード4

add_action( 'woocommerce_cart_calculate_fees', 'add_shipping_fee_based_on_distance' );
function add_shipping_fee_based_on_distance() {
    global $woocommerce;
    $shipping_distance = 20; // 配送距離を20kmと仮定
    $fee_per_km = 1; // 1kmあたりの費用
    $shipping_fee = $shipping_distance * $fee_per_km;
    $woocommerce->cart->add_fee( '配送手数料', $shipping_fee );
}

このサンプルコードは、配送距離に基づいて手数料を追加します。配送距離が20kmの場合、20ドルの配送手数料が加算されます。

サンプルコード5

add_action( 'woocommerce_cart_calculate_fees', 'apply_membership_discount' );
function apply_membership_discount() {
    global $woocommerce;
    $is_member = true; // 会員の判定(ここでは仮定)
    if ( $is_member ) {
        $discount = 15; // 会員割引
        $woocommerce->cart->add_fee( '会員割引', -$discount );
    }
}

このサンプルコードは、顧客が会員である場合に15ドルの会員割引を適用します。

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


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