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

概要

woocommerce_order_before_calculate_totalsアクションは、WooCommerce(バージョン4.0以降)において、カートや注文の金額を計算する前にカスタム処理を実行するためのフックです。このフックは、特定の条件に基づいて注文の合計金額を変更する場合や、さまざまなカスタムロジックを組み込むためによく使われます。以下は、このアクションが利用可能な場合の目的としてよく挙げられる機能の例です。

  1. カスタム割引の適用
  2. 特定条件下での手数料の追加
  3. クーポンやプロモーションの適用ロジックの追加
  4. 顧客のユーザーロールに基づく特別プライスの設定
  5. サードパーティのサービスと統合し、リアルタイムでの価格計算
  6. 地域に応じた課税計算のカスタマイズ

構文

add_action( 'woocommerce_order_before_calculate_totals', 'your_function_name' );

パラメータ

  • $order (WC_Orderインスタンス): 現在の注文オブジェクト。

戻り値

このアクションは、特定の値を返すものではありませんが、実行中に $order オブジェクトに対して変更を加えることができます。

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

  • WooCommerceバージョン: 4.0以降
  • WordPressバージョン: 5.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_order_before_calculate_totals', 'apply_custom_discount' );

function apply_custom_discount( $order ) {
    $discount = 10; // 固定割引額
    $order->set_discount_total( $discount );
    $order->set_total( $order->get_total() - $discount );
}

このコードは、注文の合計金額から固定の割引額を適用するものです。

サンプルコード 2

add_action( 'woocommerce_order_before_calculate_totals', 'add_custom_fee' );

function add_custom_fee( $order ) {
    $fee = 5; // 手数料
    $order->add_fee( 'カスタム手数料', $fee );
}

このサンプルでは、カスタム手数料を追加し、最終的な合計にその手数料が最終的に反映されます。

サンプルコード 3

add_action( 'woocommerce_order_before_calculate_totals', 'apply_special_role_discount' );

function apply_special_role_discount( $order ) {
    if ( current_user_can( 'special_role' ) ) {
        $discount = 15; // ユーザーロールに基づく割引
        $order->set_discount_total( $discount );
        $order->set_total( $order->get_total() - $discount );
    }
}

このコードは、特定のユーザインターフェースに基づいた割引を適用します。

サンプルコード 4

add_action( 'woocommerce_order_before_calculate_totals', 'calculate_tax_based_on_location' );

function calculate_tax_based_on_location( $order ) {
    $location = $order->get_shipping_address_1(); // 例:住所から取得した地域に基づく
    if ($location === 'Tokyo') {
        $tax_rate = 0.1; // 東京の税率
        $order->set_shipping_tax( $order->get_shipping_total() * $tax_rate );
    }
}

このサンプルでは、配送先の地域に応じて税金を計算し、適用されます。

サンプルコード 5

add_action( 'woocommerce_order_before_calculate_totals', 'apply_promotion_code' );

function apply_promotion_code( $order ) {
    if ( isset($_POST['promo_code']) && $_POST['promo_code'] === 'SUMMER2023' ) {
        $discount = 20; // プロモーションコードに基づく割引
        $order->set_discount_total( $discount );
        $order->set_total( $order->get_total() - $discount );
    }
}

このコードは、特定のプロモーションコードが提出された場合に割引を適用します。

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


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