概要
woocommerce_checkout_order_processed
アクションは、WooCommerceでの購入手続きが完了した際に発火します。このフックを使用することで、注文が処理された後のカスタマイズや追加の処理を行うことができます。主に以下のような機能を実装する際に使われます。
- 支払い処理の追加
- 注文データのカスタマイズ
- 外部サービスとの連携
- 注文確認メールのカスタマイズ
- トラッキング情報の追加
- クーポンコードの適用
構文
do_action('woocommerce_checkout_order_processed', $order_id, $posted_data, $order);
パラメータ
$order_id
(int): 注文のID$posted_data
(array): フォームから送信されたデータ$order
(WC_Order): 注文オブジェクト
戻り値
このアクション自体は値を返しませんが、関連する処理の結果をアクション内で処理することができます。
使用可能なバージョン
- WooCommerce バージョン: 3.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_action('woocommerce_checkout_order_processed', 'send_custom_email', 10, 3);
function send_custom_email($order_id, $posted_data, $order) {
$to = 'example@example.com';
$subject = 'New Order Received';
$message = 'An order has been processed with ID: ' . $order_id;
wp_mail($to, $subject, $message);
}
引用元: https://docs.woocommerce.com/document/
サンプル2: 購入完了後のストック管理
このコードは、注文が処理された後に特定の製品の在庫を減少させる処理を行います。
add_action('woocommerce_checkout_order_processed', 'decrement_stock', 10, 3);
function decrement_stock($order_id, $posted_data, $order) {
foreach ($order->get_items() as $item_id => $item) {
$product = $item->get_product();
if ($product) {
$stock_quantity = $product->get_stock_quantity();
if ($stock_quantity) {
$product->set_stock_quantity($stock_quantity - $item->get_quantity());
$product->save();
}
}
}
}
引用元: https://woocommerce.wordpress.com/
サンプル3: 外部APIへのデータ送信
このサンプルコードでは、注文処理後に外部のAPIへ注文情報を送信する例を示します。
add_action('woocommerce_checkout_order_processed', 'send_order_to_external_api', 10, 3);
function send_order_to_external_api($order_id, $posted_data, $order) {
$response = wp_remote_post('https://api.example.com/orders', [
'body' => json_encode($order->get_data()),
'headers' => ['Content-Type' => 'application/json'],
]);
}
引用元: https://developer.wordpress.org/
サンプル4: 注文完了時にクーポンの使用状況を記録
このコードは、注文の処理後に使用したクーポンをデータベースに記録する機能を実装します。
add_action('woocommerce_checkout_order_processed', 'log_used_coupons', 10, 3);
function log_used_coupons($order_id, $posted_data, $order) {
$coupons = $order->get_used_coupons();
foreach ($coupons as $coupon) {
// ここでデータベースにクーポンを記録する処理を行います
}
}
引用元: https://easywp.com/
サンプル5: 注文のステータスを変更
このコードでは、注文が処理された後に注文ステータスを変更する例を示します。
add_action('woocommerce_checkout_order_processed', 'change_order_status', 10, 3);
function change_order_status($order_id, $posted_data, $order) {
$order->update_status('processing', 'Order is being processed.');
}
引用元: https://woocommerce.com/document/