概要
woocommerce_order_object_updated_props
アクションは、WooCommerceにおいて注文オブジェクトのプロパティが更新された際にトリガーされるフックです。このアクションは、特に以下の機能を実装する際に頻繁に利用されます。
- 注文ステータスの変更に応じた通知の送信。
- カスタムフィールドの更新や再計算。
- 外部システムとのデータ同期。
- 注文情報のロギング。
- ユーザーによるアクションをトリガーするカスタムフックの設置。
- 他のプラグインとの後処理や統合。
構文
do_action( 'woocommerce_order_object_updated_props', $order, $updated_props );
パラメータ
$order
(WC_Order): 更新された注文オブジェクト。$updated_props
(array): 更新されたプロパティの配列。
戻り値
このアクション自体は何も返しません。
使用可能なプラグインバージョン
- WooCommerce: 3.0以上
- WordPress: 4.0以上
サンプルコード
サンプル1: 注文ステータスが変更されたときに通知を送る
このコードは、注文ステータスが更新された際にカスタムメールを送信します。
add_action( 'woocommerce_order_object_updated_props', 'send_custom_order_notification', 10, 2 );
function send_custom_order_notification( $order, $updated_props ) {
if ( isset( $updated_props['status'] ) ) {
$to = 'admin@example.com';
$subject = 'Order Status Updated';
$message = 'Order #' . $order->get_id() . ' status has been updated to ' . $updated_props['status'];
wp_mail( $to, $subject, $message );
}
}
サンプル2: 注文情報のロギング
このコードは、更新された注文情報をログファイルに記録します。
add_action( 'woocommerce_order_object_updated_props', 'log_order_updates', 10, 2 );
function log_order_updates( $order, $updated_props ) {
$log = 'Order ID: ' . $order->get_id() . ' updated with properties: ' . json_encode( $updated_props );
error_log( $log );
}
サンプル3: カスタムフィールドをリセット
このコードは、注文が更新されたときにカスタムフィールドをリセットします。
add_action( 'woocommerce_order_object_updated_props', 'reset_custom_field_on_order_update', 10, 2 );
function reset_custom_field_on_order_update( $order, $updated_props ) {
if ( ! empty( $updated_props ) ) {
$order->update_meta_data( 'custom_field_key', '' );
$order->save();
}
}
サンプル4: 外部システムとのデータ同期
このコードは、注文が更新されたときに外部APIと同期を行います。
add_action( 'woocommerce_order_object_updated_props', 'sync_order_with_external_api', 10, 2 );
function sync_order_with_external_api( $order, $updated_props ) {
if ( isset( $updated_props['total'] ) ) {
$api_url = 'https://api.example.com/orders/' . $order->get_id();
$data = [
'total' => $order->get_total(),
'status' => $updated_props['status'],
];
wp_remote_post( $api_url, [
'body' => json_encode( $data ),
'headers' => [ 'Content-Type' => 'application/json' ],
]);
}
}
サンプル5: ユーザーへの通知
このコードは、注文が更新されたときにユーザーに通知を送信します。
add_action( 'woocommerce_order_object_updated_props', 'notify_user_on_order_update', 10, 2 );
function notify_user_on_order_update( $order, $updated_props ) {
$user_id = $order->get_user_id();
if ( $user_id ) {
$to = get_userdata( $user_id )->user_email;
$subject = 'Your Order Has Been Updated';
$message = 'Your order #' . $order->get_id() . ' has been updated.';
wp_mail( $to, $subject, $message );
}
}
この関数のアクションでの使用可能性
アクション | 使用例 |
---|---|
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 |