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

概要

woocommerce_add_to_cart アクションは、WooCommerceで商品がカートに追加される際に発火するフックです。このアクションは、さまざまな機能を実装する際に役立ちます。具体的には、以下のようなシナリオでよく使用されます:

  1. カートに商品を追加した際のログ記録
  2. 特定の商品の在庫チェック
  3. ユーザーへのメッセージ表示
  4. 関連する商品を自動的にカートに追加
  5. 追加された商品のプロモーション情報の表示
  6. 他のプラグインとの連携処理

構文

do_action( 'woocommerce_add_to_cart', $product_id, $quantity, $variation_id, $cart_item_data );

パラメータ

  • $product_id (int): カートに追加される商品のID
  • $quantity (int): 追加される商品の数量
  • $variation_id (int): 設定されている場合、商品の変種ID
  • $cart_item_data (array): カートアイテムに関連するデータの配列

戻り値

このアクションは、戻り値を持ちませんが、フック内でカスタマイズされた機能を実行します。

バージョン情報

  • WooCommerce バージョン: すべてのバージョン
  • WordPress バージョン: すべてのバージョン

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

アクション名 使用例
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_action( 'woocommerce_add_to_cart', 'custom_add_to_cart_message', 10, 4 );

function custom_add_to_cart_message( $product_id, $quantity, $variation_id, $cart_item_data ) {
    wc_add_notice( '商品がカートに追加されました!', 'success' );
}

このコードは、カートに商品が追加された際に、成功メッセージを表示させます。

サンプルコード2: 在庫チェックの実装

add_action( 'woocommerce_add_to_cart', 'check_stock_before_adding', 10, 2 );

function check_stock_before_adding( $product_id, $quantity ) {
    $product = wc_get_product( $product_id );
    if ( ! $product->is_in_stock() ) {
        wc_add_notice( 'この商品は在庫切れです。', 'error' );
    }
}

このコードは、商品がカートに追加される前に在庫があるかどうかを確認し、在庫がない場合にはエラーメッセージを表示します。

サンプルコード3: 特定商品の自動追加

add_action( 'woocommerce_add_to_cart', 'add_related_product_to_cart', 10, 4 );

function add_related_product_to_cart( $product_id, $quantity, $variation_id, $cart_item_data ) {
    if ( $product_id == 123 ) { // 商品IDが123の場合
        WC()->cart->add_to_cart( 456 ); // 商品IDが456の関連商品を追加
    }
}

このコードは、特定の商品のカート追加時に、別の商品を自動的にカートに追加します。

サンプルコード4: カートに商品を追加した時のログ記録

add_action( 'woocommerce_add_to_cart', 'log_add_to_cart_action', 10, 4 );

function log_add_to_cart_action( $product_id, $quantity, $variation_id, $cart_item_data ) {
    error_log( 'Product added to cart: ' . $product_id );
}

このコードは、商品がカートに追加されるたびに、その商品IDをエラーログに記録します。

サンプルコード5: プロモーションメッセージの表示

add_action( 'woocommerce_add_to_cart', 'show_promotion_message', 10, 4 );

function show_promotion_message( $product_id, $quantity, $variation_id, $cart_item_data ) {
    if ( $product_id == 789 ) { // 商品IDが789の場合
        wc_add_notice( 'この商品には10%の割引があります!', 'notice' );
    }
}

このコードは、特定の商品がカートに追加された場合に、プロモーションメッセージを表示します。

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


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