概要
woocommerce_cart_item_class
フィルタは、WooCommerceのカート内のアイテムに特定のCSSクラスを追加または変更するためのフックです。このフィルタを使用することで、カートに表示されるアイテムの見た目をカスタマイズしたり、特定の条件に基づいてアイテムに異なるクラスを付与することができます。主に以下のような機能を実装する際によく使用されます。
- 特定のアイテムに特別なスタイルを適用。
- アイテムの種類に基づいてクラスを動的に変更。
- プロモーションやバンドル商品のステータスを表示。
- ロジックにしたがったアイテムのアクティブ状態の表現。
- カート内のアイテムに対する動的なカスタマイズの実現。
- 条件付きで異なるクラス名を付与し、JavaScriptやCSSでの操作の容易化。
構文
add_filter( 'woocommerce_cart_item_class', 'your_custom_class_function', 10, 3 );
パラメータ
$class
: 既定のCSSクラスの一覧$cart_item
: カートアイテムのデータ$cart_item_key
: カートアイテムのキー
戻り値
フィルタ処理後のカスタマイズされたCSSクラスの文字列。
使用可能なバージョン
- WooCommerce: バージョン3.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 |
サンプルコード
-
特定のアイテムに特別なスタイルを追加する
add_filter( 'woocommerce_cart_item_class', 'add_special_class_to_item', 10, 3 ); function add_special_class_to_item( $class, $cart_item, $cart_item_key ) { if ( isset( $cart_item['data'] ) && $cart_item['data']->get_id() === 123 ) { $class .= ' special-item-class'; } return $class; }
このサンプルコードは、商品のIDが123であるカートアイテムに「special-item-class」というCSSクラスを追加します。
引用元: https://woocommerce.com
-
クラスをアイテムの種類に基づいて変更する
add_filter( 'woocommerce_cart_item_class', 'change_class_by_product_type', 10, 3 ); function change_class_by_product_type( $class, $cart_item, $cart_item_key ) { $product_type = $cart_item['data']->get_type(); if ( $product_type === 'simple' ) { $class .= ' simple-product'; } return $class; }
このコードは、カートにあるシンプルな商品のアイテムに「simple-product」というクラスを追加します。
引用元: https://woocommerce.com
-
ディスカウントアイテムにスタイルを適用
add_filter( 'woocommerce_cart_item_class', 'discounted_item_class', 10, 3 ); function discounted_item_class( $class, $cart_item, $cart_item_key ) { if ( isset( $cart_item['data'] ) && $cart_item['data']->is_on_sale() ) { $class .= ' discounted-item'; } return $class; }
このサンプルでは、割引中のアイテムに「discounted-item」というクラスを追加します。
引用元: https://woocommerce.com
-
特別プロモーションアイテムのハイライト
add_filter( 'woocommerce_cart_item_class', 'highlight_promo_item_class', 10, 3 ); function highlight_promo_item_class( $class, $cart_item, $cart_item_key ) { if ( isset( $cart_item['data'] ) && $cart_item['data']->get_meta( 'is_promo', true ) ) { $class .= ' promo-highlight'; } return $class; }
このコードは、プロモーション用に設定されたアイテムに「promo-highlight」というクラスを追加します。
引用元: https://woocommerce.com
-
在庫切れアイテムに警告スタイルを付与
add_filter( 'woocommerce_cart_item_class', 'out_of_stock_warning_class', 10, 3 ); function out_of_stock_warning_class( $class, $cart_item, $cart_item_key ) { if ( isset( $cart_item['data'] ) && ! $cart_item['data']->is_in_stock() ) { $class .= ' out-of-stock-warning'; } return $class; }
このサンプルは、在庫切れの商品に「out-of-stock-warning」というクラスを追加し、ユーザーが注意できるようにします。
引用元: https://woocommerce.com