概要
フィルタ woocommerce_calculate_item_totals_taxes
は、WooCommerceでカートのアイテムの合計金額を計算する際に、税金に関する情報を変更または追加するために使用されます。このフィルタは、アイテムごとの税金を操作するために非常に便利で、特に以下のような機能を実装する際によく使われます。
- カスタム税率の適用
- 税金の計算ロジックの変更
- 割引と税金の計算の統合
- 複雑な税金構造の実装
- 特定の条件に基づく税金の軽減
- 場所に依存する税金の計算のカスタマイズ
フィルタの構文は以下の通りです。
add_filter('woocommerce_calculate_item_totals_taxes', 'callback_function', 10, 4);
パラメータ
- $taxes: 現在の税金の配列。
- $cart_item: カートアイテムの配列。
- $cart_item_key: カートアイテムのキー。
- $cart: 現在のカートオブジェクト。
戻り値
- 変更された税金の配列。
使用可能なプラグインおよびバージョン
- 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_calculate_item_totals_taxes', 'custom_tax_calculation', 10, 4);
function custom_tax_calculation($taxes, $cart_item, $cart_item_key, $cart) {
// カートアイテムのカスタム税率を適用する。
$custom_tax_rate = 0.05; // 5%のカスタム税率
$taxes[] = $cart_item['data']->get_price() * $custom_tax_rate;
return $taxes;
}
このサンプルコードは、カートアイテムの価格に対して5%のカスタム税率を適用し、それを税金の配列に追加します。
サンプルコード2
add_filter('woocommerce_calculate_item_totals_taxes', 'modify_tax_array', 10, 4);
function modify_tax_array($taxes, $cart_item, $cart_item_key, $cart) {
// 特定の商品の税率を変更する。
if ($cart_item['product_id'] == 123) { // 商品IDが123の場合
$taxes = array(0.10 * $cart_item['data']->get_price()); // 10%の税率
}
return $taxes;
}
このコードは、特定の商品IDに対して10%の税率を適用するサンプルです。
サンプルコード3
add_filter('woocommerce_calculate_item_totals_taxes', 'apply_discounted_tax_rate', 10, 4);
function apply_discounted_tax_rate($taxes, $cart_item, $cart_item_key, $cart) {
if ($cart_item['quantity'] > 1) {
$discounted_tax_rate = 0.03; // 3%の割引税率
$taxes[] = $cart_item['data']->get_price() * $discounted_tax_rate;
}
return $taxes;
}
このサンプルコードは、数量が1より多い場合に3%の割引税率を適用します。
サンプルコード4
add_filter('woocommerce_calculate_item_totals_taxes', 'conditional_tax_application', 10, 4);
function conditional_tax_application($taxes, $cart_item, $cart_item_key, $cart) {
if (isset($cart_item['data']) && $cart_item['data']->is_in_stock()) {
$tax_rate = 0.07; // 在庫がある商品の税率
$taxes[] = $cart_item['data']->get_price() * $tax_rate;
}
return $taxes;
}
このコードでは、在庫がある商品のみ税金を計算します。
サンプルコード5
add_filter('woocommerce_calculate_item_totals_taxes', 'custom_tax_logic_based_on_location', 10, 4);
function custom_tax_logic_based_on_location($taxes, $cart_item, $cart_item_key, $cart) {
$user_location = WC()->customer->get_shipping_country(); // ユーザーの配送先国を取得
if ($user_location == 'JP') { // 日本の場合
$taxes[] = $cart_item['data']->get_price() * 0.10; // 10%の税率
}
return $taxes;
}
このサンプルコードは、ユーザーの配送先が日本の場合に10%の税率を適用します。