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

概要

woocommerce_checkout_create_orderアクションは、WooCommerceのチェックアウトプロセス中に、注文が作成される際に実行されるフックです。このアクションは、カスタムロジックや追加のデータ処理が必要な場合に非常に便利です。以下のような機能を実装する際に使用されることが一般的です。

  1. 注文メタデータの追加
  2. 顧客情報の検証
  3. カスタムフィールドの保存
  4. 注文状況のトラッキング
  5. 他システムへのデータ送信
  6. 特別な割引やプロモーションの適用

構文

add_action('woocommerce_checkout_create_order', 'your_function_name', 10, 2);

パラメータ

  • $order (WC_Order): 新しく作成される注文オブジェクト
  • $data (array): チェックアウト時のデータ

戻り値

このアクションからの戻り値は特になく、主に$orderオブジェクトに対する変更が行われます。

バージョン情報

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

サンプルコード

サンプル1: 注文メタデータの追加

このサンプルコードは、カスタムメタデータを注文に追加する方法を示しています。

add_action('woocommerce_checkout_create_order', 'add_custom_meta_to_order', 10, 2);
function add_custom_meta_to_order($order, $data) {
    $order->update_meta_data('custom_meta_key', 'Custom Value');
}

引用元: https://woocommerce.com/document/

サンプル2: 顧客情報の検証

このコードでは、特定の条件に基づいて顧客情報を検証し、問題がある場合はエラーメッセージを表示します。

add_action('woocommerce_checkout_create_order', 'validate_customer_information', 10, 2);
function validate_customer_information($order, $data) {
    if (empty($data['billing']['billing_phone'])) {
        wc_add_notice(__('電話番号が必須です。'), 'error');
    }
}

引用元: https://woocommerce.com/document/

サンプル3: 特別な割引の適用

このサンプルでは、特定の条件に基づいて割引を適用しています。

add_action('woocommerce_checkout_create_order', 'apply_special_discount', 10, 2);
function apply_special_discount($order, $data) {
    if ($data['billing']['billing_country'] === 'JP') { // 日本からの購入
        $order->set_discount_total(10); // 10ドル割引
        $order->set_cart_discount(10);
    }
}

引用元: https://woocommerce.com/document/

サンプル4: 他システムへのデータ送信

このコードでは、注文が作成された際に外部システムにデータを送信します。

add_action('woocommerce_checkout_create_order', 'send_order_data_to_external_system', 10, 2);
function send_order_data_to_external_system($order, $data) {
    $order_data = $order->get_data();
    // データを外部APIに送信する処理を追加
}

引用元: https://woocommerce.com/document/

サンプル5: カスタムフィールドの保存

このコードは、カスタムフィールドのデータを保存するためのものです。

add_action('woocommerce_checkout_create_order', 'save_custom_fields', 10, 2);
function save_custom_fields($order, $data) {
    if (isset($_POST['custom_field'])) {
        $order->update_meta_data('custom_field', sanitize_text_field($_POST['custom_field']));
    }
}

引用元: https://woocommerce.com/document/

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

アクション 使用可否
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

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


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