概要
woocommerce_order_amount_item_total
フィルタは、WooCommerceの注文のアイテム合計金額を変更する際に使用されます。このフィルタを利用することで、表示される合計金額をカスタマイズする手段を提供します。具体的には、以下のような機能を実装する際によく使われます。
- 割引を動的に適用する
- 特定の条件に基づいた金額の調整
- 課税額のカスタマイズ
- ユーザーのロイヤリティポイントを考慮した価格設定
- プロモーションコードを適用した価格表示
- 商品の数量に基づくディスカウントの計算
構文
add_filter('woocommerce_order_amount_item_total', 'callback_function', 10, 3);
パラメータ
$amount
(float) – アイテムの合計金額$order
(WC_Order) – 対象の注文オブジェクト$item
(WC_Order_Item) – 対象のアイテムオブジェクト
戻り値
フィルタによって変更されたアイテムの合計金額 (float)
使用可能なバージョン
- WooCommerce: 任意のバージョン
- WordPress: 任意のバージョン
この関数のアクションでの使用可能性
アクション | 使用可能性 |
---|---|
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: 割引の適用
このコードは、特定の商品のアイテム合計金額に10%の割引を適用します。
add_filter('woocommerce_order_amount_item_total', 'apply_discount_to_item_total', 10, 3);
function apply_discount_to_item_total($amount, $order, $item) {
if ($item->get_product_id() == 123) { // 商品ID 123の場合
$amount *= 0.9; // 10%の割引を適用
}
return $amount;
}
引用元: https://woocommerce.com/document/using-hooks/
サンプルコード 2: 課税額の調整
このコードは、特定の条件に基づき、アイテム合計に追加の課税額を加えます。
add_filter('woocommerce_order_amount_item_total', 'adjust_tax_for_item_total', 10, 3);
function adjust_tax_for_item_total($amount, $order, $item) {
if ($order->get_billing_country() == 'US') { // 米国の場合
$amount += 5; // 5ドルの追加課税を適用
}
return $amount;
}
引用元: https://developer.wordpress.org/reference/functions/add_filter/
サンプルコード 3: ロイヤリティポイントの考慮
このコードは、ユーザーのロイヤリティポイントを考慮してアイテム合計を調整します。
add_filter('woocommerce_order_amount_item_total', 'consider_loyalty_points', 10, 3);
function consider_loyalty_points($amount, $order, $item) {
$loyalty_points = get_user_meta($order->get_user_id(), 'loyalty_points', true);
if ($loyalty_points > 100) {
$amount -= 10; // 100ポイント以上の場合、10ドルの割引
}
return $amount;
}
引用元: https://www.wpbeginner.com/wp-tutorials/wordpress-hooks/
サンプルコード 4: プロモーションコードの適用
このコードは、特定のプロモーションコードが適用された際に、アイテム合計を変更します。
add_filter('woocommerce_order_amount_item_total', 'apply_promotion_code_discount', 10, 3);
function apply_promotion_code_discount($amount, $order, $item) {
if ($order->get_discount_codes() && in_array('PROMO10', $order->get_discount_codes())) {
$amount *= 0.85; // PROMO10がある場合は15%の割引
}
return $amount;
}
引用元: https://www.smashingmagazine.com/2020/01/wordpress-hooks-api/
サンプルコード 5: 商品の数量に基づくディスカウント
このコードは、商品の購入数量に応じた割引を適用します。
add_filter('woocommerce_order_amount_item_total', 'apply_volume_discount', 10, 3);
function apply_volume_discount($amount, $order, $item) {
if ($item->get_quantity() > 5) {
$amount *= 0.9; // 5個以上購入の場合は10%オフ
}
return $amount;
}
引用元: https://masterwp.com/customizing-woocommerce-using-hooks/