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

概要

woocommerce_cancelled_order アクションは、WooCommerceで注文がキャンセルされたときにトリガーされるフックです。このアクションを使用することで、キャンセルされた注文に対して特定の処理を実行できるため、以下のようなシナリオでよく使われます。

  1. キャンセルされた注文に関連するメール通知の送信
  2. 在庫の回復
  3. キャンセル処理のログ記録
  4. マーケティングリストからの顧客情報の削除
  5. アカウントの利用制限または更新
  6. カスタムキャンセル処理の実行

構文

add_action( 'woocommerce_cancelled_order', 'your_custom_function', 10, 1 );

パラメータ

  • $order: キャンセルされた注文のオブジェクトです。このオブジェクトを使って、注文に関連する情報(アイテム、金額、顧客情報など)にアクセスできます。

戻り値

このアクション自体は何も戻り値を返しませんが、フック内でカスタム処理を実行できます。

使用可能なプラグインおよびバージョン

  • WooCommerceバージョン: 5.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_cancelled_order', 'send_cancelled_order_email', 10, 1 );

function send_cancelled_order_email( $order ) {
    $mailer = WC()->mailer();
    $recipient = get_option('admin_email');
    $subject = '注文がキャンセルされました';
    $message = '次の注文がキャンセルされました: ' . $order->get_order_number();

    $mailer->send( $recipient, $subject, $message );
}

このサンプルコードは、キャンセルされた注文の詳細を管理者にメールで通知します。

サンプルコード2: 在庫の回復

add_action( 'woocommerce_cancelled_order', 'restore_stock_on_cancellation', 10, 1 );

function restore_stock_on_cancellation( $order ) {
    foreach ( $order->get_items() as $item_id => $item ) {
        $product = $item->get_product();
        $product->set_stock_quantity( $product->get_stock_quantity() + $item->get_quantity() );
        $product->save();
    }
}

このコードは、キャンセルされた注文の商品在庫を元に戻します。

サンプルコード3: キャンセル処理のログ記録

add_action( 'woocommerce_cancelled_order', 'log_cancelled_order', 10, 1 );

function log_cancelled_order( $order ) {
    $log_entry = 'Order ' . $order->get_order_number() . ' has been cancelled.';
    error_log( $log_entry );
}

このサンプルは、キャンセルされた注文の詳細をエラーログに記録します。

サンプルコード4: フィードバックの収集

add_action( 'woocommerce_cancelled_order', 'collect_feedback_on_cancellation', 10, 1 );

function collect_feedback_on_cancellation( $order ) {
    // フィードバックを収集するためのコードをここに追加
}

このコードは、キャンセルされた注文に対して顧客からフィードバックを収集するためのフックポイントです。

サンプルコード5: リワードポイントの減少

add_action( 'woocommerce_cancelled_order', 'deduct_reward_points', 10, 1 );

function deduct_reward_points( $order ) {
    $customer_id = $order->get_customer_id();
    $points_to_deduct = $order->get_total(); // 例として総額を使用
    // リワードポイントを減少させる処理を実装
}

このサンプルコードは、キャンセルされた注文に応じて顧客のリワードポイントを減少させる処理を行います。

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


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