概要
woocommerce_order_amount_line_subtotal
はWooCommerceプラグインのフィルターフックの一つで、注文の小計に関連する値をフィルタリングできます。このフィルタは、注文の具体的な小計を変更したり、カスタマイズしたりする際によく使用されます。主に次のような機能の実装に使われます:
- 特定の条件に基づく割引の適用。
- カスタム税率の適用。
- クーポン割引の適用を反映させる。
- 小計に基づくポイントシステムの導入。
- 購入合計の表記方法の変更(通貨やフォーマット)。
- サードパーティ製の計算ロジックの組込み。
構文
add_filter( 'woocommerce_order_amount_line_subtotal', 'your_function_name', 10, 2 );
パラメータ
$subtotal
(float): 現在の小計額。$order
(WC_Order): 現在の注文オブジェクト。
戻り値
- フィルタリングされた小計の値(float)。
使用可能なプラグインWooCommerceのバージョン
- 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_subtotal', 'apply_custom_discount', 10, 2 );
function apply_custom_discount( $subtotal, $order ) {
$discount = 10; // 適用する割引額
return $subtotal - $discount;
}
このサンプルは、注文の小計に10の割引を加えています。割引を適用することで、顧客に対するインセンティブを提供する際に役立ちます。
サンプル2: 税金のカスタマイズ
add_filter( 'woocommerce_order_amount_line_subtotal', 'add_custom_tax', 10, 2 );
function add_custom_tax( $subtotal, $order ) {
$tax_rate = 1.05; // 税率を1.05(5%)に設定
return $subtotal * $tax_rate;
}
このサンプルでは、小計にカスタム税率を適用しています。ビジネス要件に基づいて税務処理を調整したい場合に便利です。
サンプル3: クーポン割引を反映する
add_filter( 'woocommerce_order_amount_line_subtotal', 'apply_coupon_discount', 10, 2 );
function apply_coupon_discount( $subtotal, $order ) {
$coupon_discount = $order->get_discount_total(); // クーポンの割引を取得
return $subtotal - $coupon_discount;
}
このサンプルは、注文に適用されているクーポン割引を考慮して小計を調整します。クーポンを利用したプロモーションで使用されることが多いです。
サンプル4: カスタムフォーマットの適用
add_filter( 'woocommerce_order_amount_line_subtotal', 'custom_subtotal_format', 10, 2 );
function custom_subtotal_format( $subtotal, $order ) {
return number_format($subtotal, 2) . '円';
}
このサンプルは、小計を特定のフォーマットで表示します。通貨の単位を追加し、視覚的にわかりやすくするために役立ちます。
サンプル5: 特定条件での調整
add_filter( 'woocommerce_order_amount_line_subtotal', 'conditional_subtotal_adjustment', 10, 2 );
function conditional_subtotal_adjustment( $subtotal, $order ) {
if ( $order->get_total() > 5000 ) { // 注文合計が5000以上のとき
return $subtotal * 0.90; // 10%の割引を適用
}
return $subtotal;
}
このサンプルは、注文合計が特定の金額を超えた場合に小計を調整しています。概要に示したように、特定の条件でインセンティブを与える際に有用です。