概要
woocommerce_update_order_item
アクションは、WooCommerceで注文商品が更新された際に発火するフックです。このアクションは、商品の数量やメタデータを変更する際に便利であり、注文管理機能において特に有用です。サイトの運営者や開発者は、このアクションを使ってさまざまなカスタマイズを実装することができます。以下は、主な使用ケースの一例です。
- 注文商品のメタデータを更新する
- 顧客への通知をトリガーする
- 在庫状況の更新を行う
- レポート作成データを記録する
- サードパーティサービスとの連携を行う
- ログ記録やデバッグのための情報を保存する
構文
do_action( 'woocommerce_update_order_item', $item_id, $item, $order_id );
パラメータ
$item_id
: 更新された商品アイテムのID。$item
: 更新された商品アイテムのデータ。$order_id
: 対応する注文のID。
戻り値
このアクションは戻り値を返しません。
使用可能なプラグイン
- WooCommerce バージョン: 4.0以降
- WordPress バージョン: 5.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_update_order_item', 'log_updated_order_item', 10, 3 );
function log_updated_order_item( $item_id, $item, $order_id ) {
$order_item = wc_get_order_item( $item_id );
error_log( 'Updated item ID: ' . $item_id . ', Quantity: ' . $order_item->get_quantity() );
}
このコードは、注文アイテムの数量を更新した際に、その情報をWordPressのエラーログに記録します。
サンプルコード2: 注文アイテムが更新されたときに通知を送信する
add_action( 'woocommerce_update_order_item', 'send_notification_on_update', 10, 3 );
function send_notification_on_update( $item_id, $item, $order_id ) {
$order = wc_get_order( $order_id );
$to = $order->get_billing_email();
wp_mail( $to, 'Order Item Updated', 'An item in your order has been updated.' );
}
このコードは、注文アイテムが更新されると、顧客にその旨の通知メールを送信します。
サンプルコード3: 在庫が更新されたかどうかを確認する
add_action( 'woocommerce_update_order_item', 'check_inventory_update', 10, 3 );
function check_inventory_update( $item_id, $item, $order_id ) {
$product_id = $item->get_product_id();
$stock_quantity = get_post_meta( $product_id, '_stock', true );
if ( $stock_quantity < 1 ) {
error_log( 'Product ID: ' . $product_id . ' is out of stock after updating order item ID: ' . $item_id );
}
}
このコードは、注文アイテムが更新された後、関連する商品の在庫がゼロになった場合に、その情報をログに記録します。
サンプルコード4: 注文アイテムのカスタムメタデータを更新する
add_action( 'woocommerce_update_order_item', 'update_custom_meta_on_order_item', 10, 3 );
function update_custom_meta_on_order_item( $item_id, $item, $order_id ) {
wc_update_order_item_meta( $item_id, 'custom_meta_key', 'New Value' );
}
このコードは、更新された注文アイテムにカスタムメタデータを追加または更新します。
サンプルコード5: 注文アイテム更新時のデバッグ情報を保存する
add_action( 'woocommerce_update_order_item', 'debug_order_item_update', 10, 3 );
function debug_order_item_update( $item_id, $item, $order_id ) {
$debug_info = array(
'item_id' => $item_id,
'order_id' => $order_id,
'item_data' => $item,
);
file_put_contents( plugin_dir_path( __FILE__ ) . 'debug.log', print_r( $debug_info, true ), FILE_APPEND );
}
このコードは、注文アイテムが更新されたときの詳細な情報をデバッグ用のログファイルに書き込みます。