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

概要

woocommerce_new_orderは、WooCommerceで新しい受注が作成されたときにフックされるアクションです。このアクションは、注文が完了した際に特定の処理を実行するためによく使用されます。以下のような機能を実装する際によく使われます。

  1. 注文確認メールの送信
  2. 外部サービスへの通知(Webhookなど)
  3. 注文データのログ保存
  4. CRMやERPシステムへの連携
  5. サードパーティのマーケティングツールへの情報送信
  6. 追加の処理のトリガー

構文

do_action( 'woocommerce_new_order', $order_id );

パラメータ

  • $order_id (int): 新しく作成された注文のID。

戻り値

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

使用可能なプラグインWooCommerceのバージョン

  • WooCommerce バージョン: 3.0.0以上
  • WordPress バージョン: 4.0.0以上

サンプルコード

サンプルコード1: 注文確定メールのカスタマイズ

このコードは、新しい注文が作成されたときにカスタムメールを送信する例です。

add_action( 'woocommerce_new_order', 'custom_send_order_email', 10, 1 );

function custom_send_order_email( $order_id ) {
    $order = wc_get_order( $order_id );
    $to = 'customer@example.com';
    $subject = 'Thank you for your order!';
    $message = 'Your order number is ' . $order->get_order_number();

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

(引用元: https://developer.woocommerce.com/)

サンプルコード2: 外部APIへの通知

このコードは、新しい注文が作成されたときに外部APIに通知を送信する例です。

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

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

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

サンプルコード3: 注文データのログ保存

このコードは、新しい注文が作成された際に、注文情報をファイルに保存する例です。

add_action( 'woocommerce_new_order', 'log_new_order', 10, 1 );

function log_new_order( $order_id ) {
    $order = wc_get_order( $order_id );
    $log_entry = 'New order created: ' . $order->get_order_number();
    error_log( $log_entry );
}

(引用元: https://www.wpbeginner.com/)

サンプルコード4: CRMへのデータ送信

このコードは、新しい注文が作成されたときにCRMにデータを送る例です。

add_action( 'woocommerce_new_order', 'send_order_to_crm', 10, 1 );

function send_order_to_crm( $order_id ) {
    $order = wc_get_order( $order_id );
    // ここにCRMのAPIへの送信ロジックを追加します。
}

(引用元: https://www.sitepoint.com/)

サンプルコード5: マーケティングツールへの情報送信

このコードは、新しい注文に関する情報をマーケティングツールに送信する例です。

add_action( 'woocommerce_new_order', 'send_order_to_marketing_tool', 10, 1 );

function send_order_to_marketing_tool( $order_id ) {
    $order = wc_get_order( $order_id );
    // マーケティングツールへの送信処理をここに記述
}

(引用元: https://woocommerce.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

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


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