概要
woocommerce_cart_item_product
は、WooCommerceのカート内の商品アイテムをカスタマイズするためのフィルターフックです。このフィルターを使用すると、カートに表示される商品のメタデータや属性を変更したり、特定の商品情報を追加したりすることができます。以下は、このフィルタがよく使われる機能の例です。
- 商品のカスタム属性の追加
- 特定の条件に基づく価格の変更
- 在庫ステータスの表示のカスタマイズ
- 商品説明の変更
- 商品画像の変更
- フィルタリングを通じてエンティティを柔軟にカスタマイズ
構文
add_filter( 'woocommerce_cart_item_product', 'your_custom_function', 10, 3 );
パラメータ
WC_Product
$product: 商品オブジェクト。- array $cart_item: カートアイテムのデータ。
- array $cart_item_key: カートアイテムのキー。
戻り値
WC_Product
$product: 修正された商品オブジェクト。
互換性
- 使用可能なプラグイン: WooCommerce
- WooCommerceのバージョン: 4.0以上
- WordPressのバージョン: 5.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_cart_item_product', 'apply_discount_to_cart_item', 10, 3 );
function apply_discount_to_cart_item( $product, $cart_item, $cart_item_key ) {
if ( $product->get_id() === 123 ) { // 商品IDが123の場合
$price = $product->get_price();
$new_price = $price * 0.9; // 10%引き
$product->set_price( $new_price );
}
return $product;
}
URL: www.example.com/docs/woocommerce-cart-item-filter
サンプル2: カート内の商品属性の追加
このコードは、カート内の商品の表示にカスタム属性を追加します。
add_filter( 'woocommerce_cart_item_product', 'add_custom_attribute_to_cart_item', 10, 3 );
function add_custom_attribute_to_cart_item( $product, $cart_item, $cart_item_key ) {
$product->add_meta_data( '_custom_attribute', '特別な説明' );
return $product;
}
URL: www.example.com/docs/woocommerce-cart-item-filter
サンプル3: 在庫情報のカスタマイズ
この例は、カート内商品の在庫ステータスをカスタマイズしています。
add_filter( 'woocommerce_cart_item_product', 'customize_stock_status_in_cart', 10, 3 );
function customize_stock_status_in_cart( $product, $cart_item, $cart_item_key ) {
if ( ! $product->is_in_stock() ) {
$product->set_stock_status( 'outofstock' );
}
return $product;
}
URL: www.example.com/docs/woocommerce-cart-item-filter
サンプル4: 商品説明の変更
このコードは、カート内に表示される商品の説明を変更します。
add_filter( 'woocommerce_cart_item_product', 'change_product_description_in_cart', 10, 3 );
function change_product_description_in_cart( $product, $cart_item, $cart_item_key ) {
$product->set_description( '新しい商品説明' );
return $product;
}
URL: www.example.com/docs/woocommerce-cart-item-filter
サンプル5: 商品画像の変更
カート内の商品画像をカスタマイズするサンプルコードです。
add_filter( 'woocommerce_cart_item_product', 'change_product_image_in_cart', 10, 3 );
function change_product_image_in_cart( $product, $cart_item, $cart_item_key ) {
$new_image_id = 456; // 新しい画像のID
$product->set_image_id( $new_image_id );
return $product;
}
URL: www.example.com/docs/woocommerce-cart-item-filter