プラグインWooCommerceのwoocommerce_email_order_meta_keysフィルタの使用方法・解説

概要

woocommerce_email_order_meta_keys フィルタは、WooCommerceが送信するメールに含まれる注文メタデータのキーを変更または追加するために使用されます。このフィルタを利用することで、顧客に送信されるメールに特定の情報を表示させることができます。例えば、カスタムフィールドのデータや、特定のプロダクトに関する情報を注文の詳細に追加することが可能です。よく使われるシナリオは以下の通りです:

  1. 特定の商品のカスタム属性をメールに追加する。
  2. 注文に関連する追加情報を表示する。
  3. クーポンコードなどのプロモーション情報を含める。
  4. 配送情報や特別な指示をメールで伝える。
  5. 購入者に特定のオファーや関連商品を知らせる。
  6. カスタムフィールドからの情報を通知メールに盛り込む。

フィルタの構文

add_filter( 'woocommerce_email_order_meta_keys', 'your_function_name' );

パラメータ

  • $meta_keys: 既存のメタデータキーの配列
  • $order: 該当の注文オブジェクト

戻り値

  • $meta_keys: 変更または追加されたメタデータキーの配列

対応バージョン

  • WooCommerceのバージョン: 2.0+
  • WordPressのバージョン: 4.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_filter( 'woocommerce_email_order_meta_keys', 'add_custom_meta_key' );

function add_custom_meta_key( $keys ) {
    $keys[] = 'custom_meta_key'; // カスタムメタキーを追加
    return $keys;
}

このコードは、カスタムメタキー「custom_meta_key」を送信するメールのメタデータに追加します。

サンプルコード2

add_filter( 'woocommerce_email_order_meta_keys', 'add_discount_code_key' );

function add_discount_code_key( $keys, $order ) {
    if ( $order->get_discount_code() ) {
        $keys[] = 'Discount Code: ' . $order->get_discount_code(); // 割引コードをメールに追加
    }
    return $keys;
}

このコードは、注文に割引コードが適用されている場合、その割引コードをメールに追加します。

サンプルコード3

add_filter( 'woocommerce_email_order_meta_keys', 'add_special_requests_key' );

function add_special_requests_key( $keys, $order ) {
    $special_requests = get_post_meta( $order->get_id(), 'special_requests', true );
    if ( ! empty( $special_requests ) ) {
        $keys[] = 'Special Requests: ' . $special_requests; // 特別なリクエストを追加
    }
    return $keys;
}

こちらのコードは、注文メタから特別なリクエストを取得し、その情報をメール本文に追加します。

サンプルコード4

add_filter( 'woocommerce_email_order_meta_keys', 'include_product_sku_key' );

function include_product_sku_key( $keys, $order ) {
    foreach ( $order->get_items() as $item_id => $item ) {
        $keys[] = 'Product SKU: ' . $item->get_product()->get_sku(); // 商品のSKUをメールに追加
    }
    return $keys;
}

このコードは、注文内の各商品のSKUをメールに追加します。

サンプルコード5

add_filter( 'woocommerce_email_order_meta_keys', 'add_order_notes_key' );

function add_order_notes_key( $keys, $order ) {
    $order_notes = $order->get_customer_note();
    if ( ! empty( $order_notes ) ) {
        $keys[] = 'Order Notes: ' . $order_notes; // 注文ノートをメールに追加
    }
    return $keys;
}

このサンプルコードでは、顧客が注文時に入力したメモ(注文ノート)をメールに追加します。

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


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