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

概要

woocommerce_email_order_items_args フィルタは、WooCommerceの注文メールで表示されるアイテムリストの引数を変更するために使用されます。このフィルタを利用することで、注文のアイテムに関連する情報をカスタマイズしたり、特定の条件に応じて表示内容を変更したりすることができます。主に以下のような機能を実装する際によく使われます。

  1. アイテムの数量表示のカスタマイズ
  2. 商品の価格表示のフォーマット変更
  3. 特定の商品のフィルタリング
  4. 注文アイテムに対するカスタムデータの追加
  5. アイテムの状態に応じた表示内容の変更
  6. メールテンプレート全体のスタイリングの適用

このフィルタは、WooCommerceのバージョン 2.0.0以降とWordPressのバージョン 4.0以降で使用可能です。

構文

add_filter('woocommerce_email_order_items_args', 'custom_function', 10, 1);

パラメータ

  • $args: 配列。メールに表示するアイテムの引数が含まれます。

戻り値

  • 修正された $args 配列。

サンプルコード

サンプルコード1: アイテム数を非表示にする

このサンプルコードは、受注メールにおいてアイテムの数量を非表示にします。

add_filter('woocommerce_email_order_items_args', 'remove_item_quantity_from_email', 10, 1);
function remove_item_quantity_from_email($args) {
    $args['show_quantity'] = false; // アイテム数量を非表示に設定
    return $args;
}

引用元: https://www.businessbloomer.com

サンプルコード2: 商品価格をカスタムフォーマットに変更

このサンプルコードは、注文メール内の商品の価格をカスタムフォーマットで表示します。

add_filter('woocommerce_email_order_items_args', 'custom_price_format_in_email', 10, 1);
function custom_price_format_in_email($args) {
    $args['price_format'] = '%1$s<span class="custom-currency">円</span>'; // カスタム通貨アイコンを追加
    return $args;
}

引用元: https://www.woothemes.com

サンプルコード3: 特定の商品をフィルタリング

このサンプルコードは、特定の商品をメールから除外します。

add_filter('woocommerce_email_order_items_args', 'filter_specific_product_from_email', 10, 1);
function filter_specific_product_from_email($args) {
    if (isset($args['order'])) {
        foreach ($args['order']->get_items() as $item_id => $item) {
            if ($item->get_product_id() == 123) { // 商品IDが123の商品を除外
                unset($args['order']->items[$item_id]);
            }
        }
    }
    return $args;
}

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

サンプルコード4: アイテムにカスタムデータを追加

このサンプルコードは、メール中のアイテムにカスタムデータを追加します。

add_filter('woocommerce_email_order_items_args', 'add_custom_data_to_email_items', 10, 1);
function add_custom_data_to_email_items($args) {
    $args['show_meta'] = true; // メタデータを表示
    return $args;
}

引用元: https://woocommerce.com

サンプルコード5: アイテムの条件に応じた表示変更

このサンプルコードは、商品の状態に基づいてアイテムの表示内容を変更します。

add_filter('woocommerce_email_order_items_args', 'conditional_display_items_in_email', 10, 1);
function conditional_display_items_in_email($args) {
    foreach ($args['order']->get_items() as $item_id => $item) {
        if ($item->get_status() !== 'completed') { // 完了していないアイテムの表示を変更
            $args['order']->items[$item_id]->set_name($item->get_name() . ' (処理中)');
        }
    }
    return $args;
}

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

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


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