概要
woocommerce_update_order_item
は、WooCommerceにおいて注文アイテムが更新された際にフックされるアクションです。このアクションは、カスタム機能を追加したり、注文アイテムのデータを調整したりする際に便利です。以下のような機能を実装する際に頻繁に使用されます。
- 注文アイテムのカスタムフィールドの更新
- 注文アイテムに基づく在庫管理の更新
- 注文アイテムに関する通知の送信
- 割引やクーポンに基づく価格の調整
- 注文アイテムのメタデータの追加や修正
- 顧客に対する特別オファーの適用
構文
do_action( 'woocommerce_update_order_item', $item_id, $item, $order_id );
パラメータ
- $item_id: 更新されたアイテムのID
- $item: 更新されたアイテムの情報オブジェクト
- $order_id: そのアイテムが属する注文のID
戻り値
このアクションは戻り値を持たず、副作用を利用して処理の実行を行います。
バージョン情報
- 使用可能なプラグイン: WooCommerce
- WooCommerceのバージョン: 任意(実装時に確認)
- WordPressのバージョン: 任意(実装時に確認)
この関数のアクションでの使用可能性
アクション名 | 使用例 |
---|---|
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', 'update_custom_field_on_order_item', 10, 3 );
function update_custom_field_on_order_item( $item_id, $item, $order_id ) {
$custom_field_value = 'Custom Value';
wc_add_order_item_meta( $item_id, '_custom_field', $custom_field_value );
}
サンプル2: 在庫を調整する
このサンプルでは、注文アイテムが更新された際に在庫を調整します。
add_action( 'woocommerce_update_order_item', 'adjust_stock_on_order_item_update', 10, 3 );
function adjust_stock_on_order_item_update( $item_id, $item, $order_id ) {
$product_id = $item->get_product_id();
$quantity = $item->get_quantity();
$product = wc_get_product( $product_id );
// 在庫を減らす
$product->reduce_stock_quantity( $quantity );
}
サンプル3: 注文アイテムに基づく通知を送信する
このコードは、特定の条件に基づいて顧客に通知を送信します。
add_action( 'woocommerce_update_order_item', 'send_notification_on_order_item_update', 10, 3 );
function send_notification_on_order_item_update( $item_id, $item, $order_id ) {
$order = wc_get_order( $order_id );
$email = $order->get_billing_email();
// メールを送信する
wp_mail( $email, 'Order Updated', 'Your order has been updated.' );
}
サンプル4: 割引の適用
このサンプルでは、商品が特定の条件を満たした場合に割引を適用します。
add_action( 'woocommerce_update_order_item', 'apply_discount_if_necessary', 10, 3 );
function apply_discount_if_necessary( $item_id, $item, $order_id ) {
$product_id = $item->get_product_id();
if ( $product_id == 123 ) { // 特定の商品ID
$item->set_total( $item->get_total() * 0.9 ); // 10%割引
$item->save();
}
}
サンプル5: 注文アイテムメタデータの追加
このコードは、注文アイテムにカスタムメタデータを追加します。
add_action( 'woocommerce_update_order_item', 'add_meta_to_order_item', 10, 3 );
function add_meta_to_order_item( $item_id, $item, $order_id ) {
$meta_key = 'additional_meta';
$meta_value = 'Some Value';
wc_add_order_item_meta( $item_id, $meta_key, $meta_value );
}
これらのサンプルコードはすべて、woocommerce_update_order_item
アクションを利用して注文アイテムの更新に関連するさまざまな処理を行っています。