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

概要

woocommerce_order_amount_line_total フィルタは、WooCommerce の注文金額の行合計を変更するために使用されます。このフィルタは、カートや注文の合計金額をカスタマイズする必要があるシナリオにおいて非常に役立ちます。具体的には、以下のような機能を実装する際によく使用されます。

  1. 割引の適用
  2. 手数料の追加
  3. 特定の条件に基づく料金の変更
  4. 税金の計算方法の変更
  5. カスタム料金の追加
  6. 複雑なクーポンロジックの実装

構文

add_filter( 'woocommerce_order_amount_line_total', 'your_custom_function', 10, 2 );

パラメータ

  • float $line_total – 現在の行合計金額
  • WC_Order_Item $item – 注文アイテム

戻り値

  • 変更された行合計金額

使用可能なプラグイン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: 割引の適用

add_filter( 'woocommerce_order_amount_line_total', 'apply_custom_discount', 10, 2 );

function apply_custom_discount( $line_total, $item ) {
    // 一定の条件に基づいて割引を適用
    if ( $item->get_product_id() === 123 ) {
        $line_total -= 5; // 商品IDが123の時、5ドルの割引を適用
    }
    return $line_total;
}

このコードでは、特定の商品(ID 123)が注文に含まれる場合、その商品の合計金額から5ドルの割引を適用します。

サンプル2: 手数料の追加

add_filter( 'woocommerce_order_amount_line_total', 'add_custom_fee', 10, 2 );

function add_custom_fee( $line_total, $item ) {
    // 特定の商品に手数料を追加
    if ( $item->get_product_id() === 456 ) {
        $line_total += 3; // 商品IDが456の時、3ドルの手数料を追加
    }
    return $line_total;
}

このコードは、特定の商品(ID 456)に対して3ドルの手数料を追加します。

サンプル3: カスタム料金の追加

add_filter( 'woocommerce_order_amount_line_total', 'add_custom_charge', 10, 2 );

function add_custom_charge( $line_total, $item ) {
    // 全ての注文行にカスタム料金を追加
    $custom_charge = 2; // 2ドルのカスタム料金
    $line_total += $custom_charge;
    return $line_total;
}

この例では、すべての注文行に対して2ドルのカスタム料金を追加します。

サンプル4: 税金の計算方法の変更

add_filter( 'woocommerce_order_amount_line_total', 'modify_tax_calculation', 10, 2 );

function modify_tax_calculation( $line_total, $item ) {
    // 税金を追加
    $tax_rate = 0.1; // 10%の税率
    $line_total *= (1 + $tax_rate);
    return $line_total;
}

このコードは、行合計に10%の税金を追加します。

サンプル5: 複雑なクーポンロジックの実装

add_filter( 'woocommerce_order_amount_line_total', 'apply_coupon_logic', 10, 2 );

function apply_coupon_logic( $line_total, $item ) {
    // 特定のクーポンが適用されている場合の処理
    if ( WC()->cart->has_discount( 'SPECIAL10' ) ) {
        $line_total *= 0.9; // 10%オフ
    }
    return $line_total;
}

この例では、SPECIAL10というクーポンが適用されている場合、行合計に10%の割引を適用します。

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


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