概要
woocommerce_order_edit_status
アクションは、WooCommerceで注文のステータスが変更されたときにトリガーされます。このフックを使用することにより、ステータスが変更された後、追加の処理を行うことが可能です。このアクションは、以下のような用途でよく使用されます。
- 注文のステータス変更時に通知を送信
- ステータスに基づいたカスタムレポートの生成
- 注文に関連する在庫の自動管理
- 顧客へのフォローアップメールの送信
- 独自の統計情報をデータベースに保存
- 外部APIへの通知
構文
do_action( 'woocommerce_order_edit_status', $order_id, $old_status, $new_status );
パラメータ
$order_id
: 編集された注文のID。$old_status
: 変更前のステータス。$new_status
: 変更後のステータス。
戻り値
このアクションは戻り値を持ちません。
プラグインバージョン
- WooCommerceバージョン: 3.0以上
- WordPressバージョン: 4.0以上
サンプルコード
サンプルコード1: ステータス変更時にメールを送信
add_action('woocommerce_order_edit_status', 'send_status_change_email', 10, 3);
function send_status_change_email($order_id, $old_status, $new_status) {
$order = wc_get_order($order_id);
$to = $order->get_billing_email();
$subject = "Order Status Changed";
$message = "Your order status has been changed from $old_status to $new_status.";
wp_mail($to, $subject, $message);
}
このコードは、注文のステータスが変更された際に、顧客へメールを送信します。
サンプルコード2: ステータス変更に基づくログの作成
add_action('woocommerce_order_edit_status', 'log_order_status_change', 10, 3);
function log_order_status_change($order_id, $old_status, $new_status) {
$log_entry = "Order ID: $order_id changed from $old_status to $new_status.";
error_log($log_entry);
}
このコードは、注文のステータス変更をログファイルに記録します。
サンプルコード3: 特定のステータスに変更時にクーポンを発行
add_action('woocommerce_order_edit_status', 'issue_coupon_on_status_change', 10, 3);
function issue_coupon_on_status_change($order_id, $old_status, $new_status) {
if ($new_status === 'completed') {
// クーポンの生成ロジック
$coupon_code = 'SPECIAL-OFFER';
// クーポンを発行する処理...
}
}
このコードは、注文が「完了」ステータスに変更された際に特定のクーポンを生成します。
サンプルコード4: 在庫管理の自動処理
add_action('woocommerce_order_edit_status', 'adjust_stock_on_order_status_change', 10, 3);
function adjust_stock_on_order_status_change($order_id, $old_status, $new_status) {
if ($new_status === 'cancelled') {
$order = wc_get_order($order_id);
foreach ($order->get_items() as $item_id => $item) {
$product_id = $item->get_product_id();
$qty = $item->get_quantity();
// 在庫を戻す処理...
}
}
}
このコードは、注文がキャンセルされた場合に在庫を戻す処理を実装しています。
サンプルコード5: ステータス変更時に外部APIにデータを送信
add_action('woocommerce_order_edit_status', 'notify_external_api_on_status_change', 10, 3);
function notify_external_api_on_status_change($order_id, $old_status, $new_status) {
$url = 'https://example.com/api/update_order';
$data = array(
'order_id' => $order_id,
'old_status' => $old_status,
'new_status' => $new_status,
);
wp_remote_post($url, array(
'method' => 'POST',
'body' => json_encode($data),
'headers' => array('Content-Type' => 'application/json'),
));
}
このコードは、注文のステータスが変更されると、外部APIにデータを送信します。
この関数のアクションでの使用可能性
アクション名 | 使用例 |
---|---|
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 |
この表は woocommerce_order_edit_status
アクションが他のアクションで使用されているかどうかを示しています。