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

概要

woocommerce_calculate_totalsは、WooCommerceのカートや注文の合計金額を計算する際にフックとして利用されるアクションです。このアクションは、カートの合計を計算するプロセスが実行される前に発火します。そのため、特定の条件に基づいて合計金額を変更したり、カスタムロジックを追加することが可能です。以下のような機能を実装する際によく使用されます。

  1. 割引の適用
  2. 税金の計算のカスタマイズ
  3. 手数料の追加
  4. 特定の商品の価格変更
  5. 運送費の動的な調整
  6. クーポンコードの管理や適用

構文

add_action('woocommerce_calculate_totals', 'my_custom_function');

パラメータ

  • 該当するパラメータは特にありませんが、関数内でいつでもカートオブジェクトにアクセスすることができます。

戻り値

このアクションは戻り値を返しませんが、関数内で合計金額を変更することができます。

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

  • WooCommerce: 2.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: 割引の適用

このサンプルでは、特定の条件下でカートの合計から割引を適用します。

add_action('woocommerce_calculate_totals', 'apply_discount_based_on_condition');

function apply_discount_based_on_condition($cart) {
    if (is_user_logged_in() && count($cart->get_cart()) > 2) {
        $discount = 10; // 10ドルの割引
        $cart->add_fee(__('Discount', 'woocommerce'), -$discount);
    }
}

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

サンプルコード2: 税金のカスタマイズ

このサンプルは特定の製品の税率を変更します。

add_action('woocommerce_calculate_totals', 'customize_tax_for_specific_product');

function customize_tax_for_specific_product($cart) {
    foreach ($cart->get_cart() as $cart_item_key => $cart_item) {
        if (isset($cart_item['product_id']) && $cart_item['product_id'] == 123) { // 商品ID 123
            $cart_item['data']->set_tax_class('Reduced Rate'); // 割引税率を適用
        }
    }
}

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

サンプルコード3: 手数料の追加

特定の条件でカートに手数料を追加します。

add_action('woocommerce_calculate_totals', 'add_custom_fee');

function add_custom_fee($cart) {
    if (!is_user_logged_in()) {
        $fee = 5; // 未ログインユーザー向けの手数料
        $cart->add_fee(__('Non-member fee', 'woocommerce'), $fee);
    }
}

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

サンプルコード4: 商品の価格変更

特定の商品に対して価格を変更します。

add_action('woocommerce_calculate_totals', 'change_product_price');

function change_product_price($cart) {
    foreach ($cart->get_cart() as $cart_item_key => $cart_item) {
        if ($cart_item['product_id'] == 456) { // 商品ID 456
            $cart_item['data']->set_price(20); // 新しい価格
        }
    }
}

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

サンプルコード5: 送料の調整

このサンプルでは、カートの合計金額に応じて送料を調整します。

add_action('woocommerce_calculate_totals', 'adjust_shipping_cost_based_on_total');

function adjust_shipping_cost_based_on_total($cart) {
    if ($cart->subtotal > 100) {
        $shipping_cost = 0; // 100ドル以上で送料を無料にする
        $cart->add_fee(__('Shipping Cost', 'woocommerce'), $shipping_cost);
    }
}

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

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


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