概要
woocommerce_delete_order_item
アクションは、WooCommerceにおける注文アイテムが削除されたときに実行されるフックです。このフックを使用することで、注文アイテムの削除時にカスタムロジックを実行することが可能です。これは、注文アイテムをデータベースから削除した後に処理を追加したい場合に特に有用です。
このアクションは、以下のような機能を実装する際によく使われます。
- 削除されたアイテムに関連するメタデータのクリーニング
- トラッキングや分析用のログの記録
- 顧客への通知やメール送信
- 不正なアイテム削除のチェック
- 削除履歴の管理
- 他のシステムとのデータ統合
構文
do_action( 'woocommerce_delete_order_item', $item_id, $order_id );
パラメータ
$item_id
(int): 削除された注文アイテムのID$order_id
(int): 削除されたアイテムが属する注文のID
戻り値
このアクションは値を返しません。
使用可能なプラグインバージョン
- WooCommerce: 3.0 以降
- WordPress: 4.0 以降
サンプルコード
サンプルコード1: 削除ログをファイルに書き込む
このコードは、削除されたアイテムのIDと関連する注文IDをログファイルに記録します。
add_action( 'woocommerce_delete_order_item', 'log_deleted_order_item', 10, 2 );
function log_deleted_order_item( $item_id, $order_id ) {
$log_file = WP_CONTENT_DIR . '/order_item_deletion.log';
$log_entry = "Item ID: $item_id from Order ID: $order_id deleted.n";
file_put_contents( $log_file, $log_entry, FILE_APPEND );
}
引用元: https://www.example.com
サンプルコード2: 削除されたアイテムのメタデータ削除
このコードは、削除された注文アイテムに関連するカスタムメタデータを削除します。
add_action( 'woocommerce_delete_order_item', 'delete_order_item_meta', 10, 2 );
function delete_order_item_meta( $item_id, $order_id ) {
delete_post_meta( $item_id, '_your_custom_meta_key' );
}
引用元: https://www.example.com
サンプルコード3: アイテム削除後の通知メールを送信
このコードは、アイテムが削除された際にサイト管理者に通知メールを送信します。
add_action( 'woocommerce_delete_order_item', 'notify_admin_order_item_deleted', 10, 2 );
function notify_admin_order_item_deleted( $item_id, $order_id ) {
$to = get_option( 'admin_email' );
$subject = 'Order Item Deleted';
$message = "An item (ID: $item_id) was deleted from Order (ID: $order_id).";
wp_mail( $to, $subject, $message );
}
引用元: https://www.example.com
サンプルコード4: 削除履歴を保存
このコードは、削除されたアイテムの履歴をデータベースに記録します。
add_action( 'woocommerce_delete_order_item', 'save_order_item_deletion_history', 10, 2 );
function save_order_item_deletion_history( $item_id, $order_id ) {
global $wpdb;
$table_name = $wpdb->prefix . 'order_item_deletion_history';
$wpdb->insert(
$table_name,
array(
'item_id' => $item_id,
'order_id' => $order_id,
'deleted_at' => current_time( 'mysql' )
)
);
}
引用元: https://www.example.com
サンプルコード5: 不正な削除チェック
このコードは、不正に削除されたアイテムを検出して、それに基づいた処理を実行します。
add_action( 'woocommerce_delete_order_item', 'check_invalid_item_deletion', 10, 2 );
function check_invalid_item_deletion( $item_id, $order_id ) {
// ロジック: 不正な削除であれば、追加の処理を実施
if ( some_check_function( $item_id ) ) {
// 不正な削除と判断した場合の処理
}
}
引用元: https://www.example.com
この関数のアクションでの使用可能性
アクション | 使用例 |
---|---|
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 |