概要
woocommerce_order_after_calculate_totals
は、WooCommerceのオーダー合計計算の後に実行されるカスタムフックです。このアクションを使用することで、合計金額の計算後に特殊な処理を実行することができます。以下のような機能の実装によく使われます:
- 特定の条件に基づくディスカウントの適用
- 独自の税金計算の実装
- カスタム手数料の追加
- 注文メタデータの更新
- ストアの報告機能の強化
- 顧客への通知のトリガー
このアクションは、WooCommerceのバージョン3.0以降で使用可能であり、WordPressのバージョン4.0以降で動作します。
構文
add_action('woocommerce_order_after_calculate_totals', 'your_custom_function', 10, 1);
パラメータ
$order
(WC_Order): 合計計算が行われたオーダーオブジェクト。
戻り値
このアクションは値を返しません。
サンプルコード
サンプル1: 割引を適用する
このサンプルコードは、特定の条件を満たす場合にオーダーに割引を適用するものです。
add_action('woocommerce_order_after_calculate_totals', 'apply_discount_if_eligible', 10, 1);
function apply_discount_if_eligible($order) {
// 特定の条件で割引を適用
if ($order->get_total() > 100) {
$discount = 10; // 10ドルの割引
$order->set_discount_total($discount);
$order->calculate_totals();
}
}
引用元: https://developer.wordpress.org/reference/hooks/
サンプル2: 独自の手数料を追加する
このサンプルは、オーダーに特定の条件に基づいて手数料を追加します。
add_action('woocommerce_order_after_calculate_totals', 'add_custom_fee', 10, 1);
function add_custom_fee($order) {
if ($order->get_items_count() > 5) {
$order->add_fee('Large Order Fee', 25);
$order->calculate_totals();
}
}
引用元: https://www.skyverge.com/blog/
サンプル3: 注文のメタデータを更新
このコードは、オーダー合計計算後にオーダーメタを更新します。
add_action('woocommerce_order_after_calculate_totals', 'update_order_meta_after_calculation', 10, 1);
function update_order_meta_after_calculation($order) {
update_post_meta($order->get_id(), '_custom_meta_key', 'some_value');
}
引用元: https://woocommerce.com/document/
サンプル4: 顧客通知をトリガー
このコードは、オーダーの合計が特定の条件を満たした場合に、顧客に通知を送信します。
add_action('woocommerce_order_after_calculate_totals', 'notify_customer_if_above_threshold', 10, 1);
function notify_customer_if_above_threshold($order) {
if ($order->get_total() > 200) {
// 顧客への通知を処理
wp_mail($order->get_billing_email(), 'Your Order Exceeds $200', 'Thank you for your order!');
}
}
引用元: https://developer.woocommerce.com/
サンプル5: カスタムロジックの実装
このコードは、特定の条件下でカスタムロジックを実行します。
add_action('woocommerce_order_after_calculate_totals', 'execute_custom_logic', 10, 1);
function execute_custom_logic($order) {
// カスタムロジックの実行
if ($order->get_items_count() < 3) {
// 何か特別な処理を実行
}
}
引用元: https://github.com/woocommerce/woocommerce
この関数のアクションでの使用可能性
アクション | 使用可能性 |
---|---|
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 |