プラグインWooCommerceのwoocommerce_trash_orderアクションの使用方法・解説

概要

woocommerce_trash_order アクションは、WooCommerceで注文がごみ箱に移動されたときに発火します。このアクションを使用することで、注文が削除された際のカスタムロジックを実装することが可能です。たとえば、注文の削除に関連する通知を送信したり、ログを記録したりするために利用されます。

このアクションは以下のような機能を実装する際によく使用されます:

  1. 注文がごみ箱に移動されたことを通知するメールの送信
  2. 注文データのバックアップを作成する機能
  3. ストレージやデータベースへの記録を行うロギング機能
  4. 特定の条件に基づくカスタムアクションのトリガー
  5. ユーザーへの通知メッセージを表示する機能
  6. 外部APIとの連携を行う機能

構文

do_action( 'woocommerce_trash_order', $order_id );

パラメータ

  • $order_id: ごみ箱に移動された注文のID (整数)

戻り値

このアクションは値を返しません。

使用可能なバージョン

  • WooCommerceバージョン: 2.1.0以降
  • WordPressバージョン: 4.0以降

サンプルコード

サンプル1: 注文削除時に通知メールを送信する

このコードは、注文がごみ箱に移動された際に、管理者に通知メールを送信します。

add_action( 'woocommerce_trash_order', 'send_order_trash_notification', 10, 1 );

function send_order_trash_notification( $order_id ) {
    $order = wc_get_order( $order_id );
    $to = get_option('admin_email');
    $subject = '注文が削除されました';
    $message = '注文ID ' . $order_id . ' がごみ箱に移動されました。';

    wp_mail( $to, $subject, $message );
}

引用元: https://developer.wordpress.org/

サンプル2: 注文データのバックアップを作成する

このコードは、ごみ箱に移動された注文のデータをカスタムテーブルにバックアップします。

add_action( 'woocommerce_trash_order', 'backup_trash_order', 10, 1 );

function backup_trash_order( $order_id ) {
    global $wpdb;

    $order = wc_get_order( $order_id );
    $data = array(
        'order_id' => $order_id,
        'order_data' => serialize( $order->get_data() ),
    );

    $wpdb->insert( 'wp_order_backup', $data );
}

引用元: https://developer.wordpress.org/

サンプル3: ログメッセージをファイルに記録する

このコードは、注文がゴミ箱に移動された際に、その情報をログファイルに記録します。

add_action( 'woocommerce_trash_order', 'log_trash_order', 10, 1 );

function log_trash_order( $order_id ) {
    $log_message = "注文ID " . $order_id . " がごみ箱に移動されました。n";
    error_log( $log_message, 3, '/var/log/trash_orders.log' );
}

引用元: https://developer.wordpress.org/

サンプル4: APIとの連携を行う

このコードは、注文がごみ箱に移動された際に外部APIに通知を送ります。

add_action( 'woocommerce_trash_order', 'notify_external_api', 10, 1 );

function notify_external_api( $order_id ) {
    $order = wc_get_order( $order_id );
    $response = wp_remote_post( 'https://example.com/api/notify', array(
        'body' => json_encode( array( 'order_id' => $order_id ) ),
        'headers' => array( 'Content-Type' => 'application/json' ),
    ));
}

引用元: https://developer.wordpress.org/

サンプル5: ユーザーへのアクションをトリガーする

このコードは、特定の条件によってユーザーにアクションメッセージを表示します。

add_action( 'woocommerce_trash_order', 'trigger_user_action', 10, 1 );

function trigger_user_action( $order_id ) {
    if ( is_user_logged_in() ) {
        $user_id = get_current_user_id();
        add_user_meta( $user_id, 'order_trashed', $order_id );
    }
}

引用元: https://developer.wordpress.org/

この関数のアクションでの使用可能性

アクション名 使用例
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

この関数について質問する


上の計算式の答えを入力してください