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

概要

woocommerce_order_before_calculate_taxes は、WooCommerceのオーダー処理中に税金計算が行われる直前にトリガーされるフックです。このフックを使用することで、税金の計算前にオーダー情報やカスタムロジックを処理できます。一般的に、次のような機能の実装を行う際に使われます。

  1. カスタム税率の適用
  2. 商品ごとの税の調整
  3. 割引やプロモーションコードによる影響の考慮
  4. 特定の条件に基づく税金の免除
  5. 商品のカテゴリに応じた異なる税計算
  6. サードパーティのAPIを利用した税率の取得

構文

add_action('woocommerce_order_before_calculate_taxes', 'your_custom_function');

function your_custom_function($order) {
    // カスタム処理をここに記述
}

パラメータ

  • $order: WC_Order オブジェクト。現在処理中のオーダー情報が含まれています。

戻り値

このアクションは何も返しません。

使用可能なWooCommerceのバージョン

このアクションはWooCommerceのバージョン3.0以降で使用可能です。

使用可能なWordPressのバージョン

このアクションはWordPressのバージョン4.0以降で使用可能です。

サンプルコード

サンプルコード1: カスタム税率を適用

このサンプルコードは、特定の条件に基づいてオーダーにカスタム税率を適用する方法を示しています。

add_action('woocommerce_order_before_calculate_taxes', 'apply_custom_tax_rate');

function apply_custom_tax_rate($order) {
    if (condition_to_apply_custom_tax()) {
        $order->set_tax_class('custom_tax_class');
    }
}

サンプルコード2: 商品ごとの税の調整

このサンプルでは、商品に対して異なる税率を設定する方法を示しています。

add_action('woocommerce_order_before_calculate_taxes', 'adjust_tax_for_items');

function adjust_tax_for_items($order) {
    foreach ($order->get_items() as $item_id => $item) {
        if ($item->get_product()->get_id() == 'specific_product_id') {
            // 商品の税率を調整
            $item->set_tax_class('reduced_tax_class');
        }
    }
}

サンプルコード3: 定期的な割引を考慮

このサンプルコードは、オーダーに適用された定期的な割引を考慮に入れる方法を示しています。

add_action('woocommerce_order_before_calculate_taxes', 'consider_recurring_discounts');

function consider_recurring_discounts($order) {
    if ($order->get_meta('_recurring_discount')) {
        $discount = $order->get_meta('_recurring_discount');
        $order->set_discount_total($discount);
    }
}

サンプルコード4: 特定の条件による税金免除

このサンプルコードは、特定の条件を満たす場合に税金を免除する様子を示しています。

add_action('woocommerce_order_before_calculate_taxes', 'exempt_tax_for_conditions');

function exempt_tax_for_conditions($order) {
    if (is_user_logged_in() && current_user_can('special_member')) {
        $order->set_discount_total($order->get_total());
    }
}

サンプルコード5: 商品カテゴリに応じた税計算

このサンプルは、商品カテゴリに応じて異なる税計算を行う方法を示しています。

add_action('woocommerce_order_before_calculate_taxes', 'calculate_tax_by_category');

function calculate_tax_by_category($order) {
    foreach ($order->get_items() as $item_id => $item) {
        $product_cats = wp_get_post_terms($item->get_product_id(), 'product_cat', array('fields' => 'ids'));
        if (in_array('tax_exempt_category', $product_cats)) {
            $item->set_tax_class('zero_rate_tax');
        }
    }
}

この関数のアクションでの使用可能性

アクション名 使用例
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

この表は、他のアクションでこの関数が使用されているかどうかを示します。

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


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