概要
woocommerce_order_amount_line_tax
フィルタは、WooCommerce での注文合計に対する行税金情報を修正またはカスタマイズするために使用されます。このフィルタを使用することで、税金のパーセンテージや計算方法などを変更することが可能です。具体的には、以下のような機能実装時に利用されることが多いです。
- 税率のカスタマイズ
- 表示形式の変更
- 税金の計算方法のオーバーライド
- 複数税率のサポート
- 課税商品の税クラスの変更
- 注文明細に表示する税金情報の拡張
構文
add_filter( 'woocommerce_order_amount_line_tax', 'custom_function_name', 10, 3 );
パラメータ
このフィルタには以下の3つの主要パラメータが渡されます。
$tax
(float): 計算された税額。$order
(WC_Order): 現在の注文オブジェクト。$line_item
(WC_Order_Item): 現在の行アイテムオブジェクト。
戻り値
このフィルタは、修正された税額を返す必要があります。デフォルトでは、元の税額($tax)が返されます。
使用可能なプラグインにおけるバージョン
- WooCommerce: 2.0.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_tax', 'custom_tax_format', 10, 3 );
function custom_tax_format( $tax, $order, $line_item ) {
// 税額をフォーマットに従って変更
return number_format( $tax, 2 ) . '円'; // 日本円で表示
}
サンプル2: 特定の行アイテムの税率を変更する
このサンプルでは、特定の行アイテムの税率を変更します。
add_filter( 'woocommerce_order_amount_line_tax', 'change_specific_tax', 10, 3 );
function change_specific_tax( $tax, $order, $line_item ) {
if ( $line_item->get_product_id() === 123 ) { // 商品IDが123の場合
return $tax * 1.1; // 10%増し
}
return $tax;
}
サンプル3: 税金計算方法をオーバーライドする
このサンプルコードでは、税金の計算方法をオーバーライドしています。
add_filter( 'woocommerce_order_amount_line_tax', 'override_tax_calculation', 10, 3 );
function override_tax_calculation( $tax, $order, $line_item ) {
return $line_item->get_total() * 0.05; // 固定5%の税金
}
サンプル4: 複数税率をサポートする
このコードサンプルでは、複数税率を考慮した税金計算を行います。
add_filter( 'woocommerce_order_amount_line_tax', 'multiple_tax_rates', 10, 3 );
function multiple_tax_rates( $tax, $order, $line_item ) {
$product_tax_class = $line_item->get_tax_class();
if ( $product_tax_class === 'reduced-rate' ) {
return $tax * 0.7; // 割引税率を適用
}
return $tax;
}
サンプル5: 商品ごとの税クラスを変更する
このサンプルでは、特定の商品に異なる税クラスを適用します。
add_filter( 'woocommerce_order_amount_line_tax', 'change_tax_class_based_on_product', 10, 3 );
function change_tax_class_based_on_product( $tax, $order, $line_item ) {
$item_product = $line_item->get_product();
if ( in_array( $item_product->get_id(), array( 10, 20, 30 ) ) ) { // 商品IDが10, 20, 30の時
return $tax * 0.08; // 8%の新税クラス
}
return $tax;
}
これらのサンプルコードを利用することで、woocommerce_order_amount_line_tax
フィルタの利用法を深く理解し、自分のサイトに欲しい機能を追加する手助けができるでしょう。