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

概要

woocommerce_order_cancelled_notice は、WooCommerceでの注文キャンセル時に特定の処理を実行するためのフックです。このアクションを利用して、キャンセル通知をカスタマイズしたり、他の機能をトリガーしたりすることができます。よく使われる機能には以下のようなものがあります。

  1. ユーザーにカスタムメッセージを通知
  2. キャンセルされた注文のデータをロギング
  3. 特定のユーザーに対するメール通知
  4. 在庫の自動更新
  5. 顧客へのフィードバックフォームの表示
  6. 代替商品の提案

構文

add_action('woocommerce_order_cancelled_notice', 'function_name', 10, 1);

パラメータ

  • $order: キャンセルされたオーダーのオブジェクト。

戻り値

このアクションは戻り値を持ちません。

使用可能なバージョン

  • WooCommerce: 3.0 以降
  • WordPress: 4.0 以降

サンプルコード

サンプル1: メール通知の送信

このサンプルコードは、注文がキャンセルされたときに顧客にメールを送信します。

add_action('woocommerce_order_cancelled_notice', 'send_cancelled_order_email', 10, 1);
function send_cancelled_order_email($order) {
    $to = $order->get_billing_email();
    $subject = 'Your Order Has Been Cancelled';
    $message = 'We are sorry to inform you that your order #' . $order->get_id() . ' has been cancelled.';
    wp_mail($to, $subject, $message);
}

サンプル2: ステータスのロギング

このコードは、キャンセルされた注文の情報をログファイルに書き込みます。

add_action('woocommerce_order_cancelled_notice', 'log_cancelled_order', 10, 1);
function log_cancelled_order($order) {
    $log = 'Order ID ' . $order->get_id() . ' was cancelled on ' . date('Y-m-d H:i:s');
    error_log($log);
}

サンプル3: 在庫の自動更新

キャンセルされた注文の商品の在庫を自動的に更新するサンプルです。

add_action('woocommerce_order_cancelled_notice', 'restock_items', 10, 1);
function restock_items($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();
    }
}

サンプル4: カスタマイズされたキャンセルメッセージの表示

このコードは、キャンセルされた注文にカスタマイズされたメッセージを表示します。

add_action('woocommerce_order_cancelled_notice', 'display_custom_cancel_message', 10, 1);
function display_custom_cancel_message($order) {
    echo '<p>Thank you for your order! Unfortunately, it has been cancelled. If you need assistance, please contact us.</p>';
}

サンプル5: 代替商品の提案

キャンセルされた注文に基づいて代替商品を表示する例です。

add_action('woocommerce_order_cancelled_notice', 'suggest_alternate_products', 10, 1);
function suggest_alternate_products($order) {
    $items = $order->get_items();
    // 代替商品のロジックを実装
    foreach ($items as $item) {
        echo '<p>Consider these similar products:</p>';
        // 各商品に対する代替品を取得・表示
    }
}

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

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

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


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