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

概要

woocommerce_add_cart_item フィルタは、WooCommerceのカートにアイテムが追加される際に、カートアイテムのデータをカスタマイズするために使用されます。このフィルタは、特定の商品の特性を追加したり、価格を変更したりする場合に特に有用です。

よく使われる機能

  1. 商品のカスタムメタデータを追加する。
  2. 割引やプロモーションの適用。
  3. 購入商品に基づく追加の送料の計算。
  4. 特定の条件に基づいて商品属性を変更。
  5. ギフトラッピングオプションの追加。
  6. タグやカテゴリに基づくカスタムメッセージの表示。

構文

add_filter('woocommerce_add_cart_item', 'my_custom_cart_item', 10, 2);

パラメータ

  • $cart_item_data (array): カートアイテムデータ。
  • $product_id (int): 商品のID。

戻り値

  • 修正された $cart_item_data (array): 変更されたカートアイテムデータ。

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

  • WooCommerceバージョン: 3.0以降
  • WordPressバージョン: 4.0以降

サンプルコード

サンプルコード1: カスタムメタデータの追加

add_filter('woocommerce_add_cart_item', 'add_custom_meta_to_cart_item', 10, 2);
function add_custom_meta_to_cart_item($cart_item_data, $product_id) {
    $cart_item_data['custom_meta'] = 'My Custom Meta Data';
    return $cart_item_data;
}

このコードは、カートにアイテムが追加される際にカスタムメタデータを追加します。

サンプルコード2: 割引の適用

add_filter('woocommerce_add_cart_item', 'apply_discount_on_cart_item', 10, 2);
function apply_discount_on_cart_item($cart_item_data, $product_id) {
    if ($product_id == 123) { // 商品ID 123 の場合
        $cart_item_data['discount'] = 10; // $10の割引を適用
    }
    return $cart_item_data;
}

このコードは、特定の商品IDに対して割引を適用します。

サンプルコード3: 追加送料の計算

add_filter('woocommerce_add_cart_item', 'add_shipping_fee', 10, 2);
function add_shipping_fee($cart_item_data, $product_id) {
    if ($product_id == 456) { // 商品ID 456 の場合
        $cart_item_data['shipping_fee'] = 5; // $5の追加送料を適用
    }
    return $cart_item_data;
}

このコードは、特定の商品に対して追加送料を計算して追加します。

サンプルコード4: ギフトラッピングオプションの追加

add_filter('woocommerce_add_cart_item', 'add_gift_wrap_option', 10, 2);
function add_gift_wrap_option($cart_item_data, $product_id) {
    $cart_item_data['gift_wrap'] = isset($_POST['gift_wrap']) ? true : false;
    return $cart_item_data;
}

このコードは、ユーザーがアイテムをギフトラッピングしたい場合にそのオプションを追加します。

サンプルコード5: カスタムメッセージの表示

add_filter('woocommerce_add_cart_item', 'add_custom_message_to_cart_item', 10, 2);
function add_custom_message_to_cart_item($cart_item_data, $product_id) {
    $cart_item_data['custom_message'] = 'Thank you for shopping with us!';
    return $cart_item_data;
}

このコードは、カートアイテムにカスタムメッセージを追加します。

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

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

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


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