概要
フィルタ woocommerce_order_get_subtotal
は、WooCommerceの注文に対する小計の計算を変更するために使用されるフックです。このフィルタは、商品の小計を取得する際にカスタマイズが必要な場面でよく使われます。以下に、よく使われるシナリオを6つ挙げます。
- 商品の割引を考慮した小計の計算
- カスタム税率を適用するための小計調整
- 会員特典価格の適用
- ディスカウントクーポンを適用した新版小計
- 配送料などの特別料金を小計に加算
- マルチ通貨対応のための小計変換
構文
add_filter('woocommerce_order_get_subtotal', 'custom_subtotal_function', 10, 2);
パラメータ
$subtotal
(float): 注文の小計$order
(WC_Order): 注文オブジェクト
戻り値
フィルタによって変更された小計(float)
使用可能なプラグインおよびバージョン
- 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_get_subtotal', 'calculate_discounted_subtotal', 10, 2);
function calculate_discounted_subtotal($subtotal, $order) {
// 割引が適用されている場合、その金額を小計から引く
if ($order->get_discount_total() > 0) {
$subtotal -= $order->get_discount_total();
}
return $subtotal;
}
このコードは、注文に適用された割引を考慮して小計を調整するものです。
サンプルコード2: 特別な会員価格の適用
add_filter('woocommerce_order_get_subtotal', 'apply_member_price', 10, 2);
function apply_member_price($subtotal, $order) {
// もし会員であれば特別価格を適用
if (is_user_member($order->get_user_id())) {
$subtotal *= 0.9; // 10%オフ
}
return $subtotal;
}
このコードは、ユーザーが会員である場合、10%のディスカウントを与える特別価格を適用します。
サンプルコード3: 税率のカスタマイズ
add_filter('woocommerce_order_get_subtotal', 'custom_tax_rate_subtotal', 10, 2);
function custom_tax_rate_subtotal($subtotal, $order) {
// カスタム税率の適用
$custom_tax_rate = 1.1; // 10%税率
return $subtotal * $custom_tax_rate;
}
このコードは、注文小計にカスタム税率を適用するものです。
サンプルコード4: マルチ通貨対応
add_filter('woocommerce_order_get_subtotal', 'convert_currency_subtotal', 10, 2);
function convert_currency_subtotal($subtotal, $order) {
// 通貨の変換
$exchange_rate = 0.009; // 例: 円からドルへの変換
return $subtotal * $exchange_rate;
}
このコードは、異なる通貨への変換を行い、小計を適切に調整します。
サンプルコード5: 配送料の追加
add_filter('woocommerce_order_get_subtotal', 'add_shipping_to_subtotal', 10, 2);
function add_shipping_to_subtotal($subtotal, $order) {
// 配送料を小計に追加
$shipping_total = $order->get_shipping_total();
return $subtotal + $shipping_total;
}
このコードは、注文の配送料を小計に追加するものです。
これらのサンプルはそれぞれ異なる目的で woocommerce_order_get_subtotal
フィルタを使用しています。