概要
woocommerce_order_item_classフィルタは、WooCommerceの注文アイテムに特定のCSSクラスを追加または変更するために使用されます。このフィルタを活用することで、より詳細なスタイリングやJavaScriptの操作など、拡張機能を加えることが可能となります。主に以下のような機能を実装する際にこのフィルタが利用されます。
- 注文アイテムの特定の状態に基づくスタイル適用
- カスタムのフロントエンド表示のためのクラス追加
- アイテムが特定のカテゴリに属する場合のスタイリング
- 在庫状況に基づくスタイル変更
- 購入した商品による特定のユーザー体験の向上
- プラグインのカスタマイズや拡張のための柔軟性向上
構文
add_filter('woocommerce_order_item_class', 'custom_order_item_class', 10, 3);
パラメータ
$classname:デフォルトのCSSクラス。$item_id:注文アイテムのID。$item:注文アイテムのデータオブジェクト。
戻り値
- 変更後のCSSクラス名(文字列)。
使用可能なバージョン
- WooCommerce バージョン:すべてのバージョン
- WordPress バージョン:すべてのバージョン
サンプルコード
サンプルコード1: 特定のアイテムにクラスを追加
add_filter('woocommerce_order_item_class', 'add_custom_class_to_order_item', 10, 2);
function add_custom_class_to_order_item($classname, $item) {
if ($item->get_product_id() === 123) { // 商品ID 123 の場合
$classname .= ' custom-class';
}
return $classname;
}
このコードは、特定の製品IDを持つ注文アイテムにcustom-classというクラスを追加します。
サンプルコード2: 在庫が少ない商品に警告クラスを追加
add_filter('woocommerce_order_item_class', 'add_warning_class_for_low_stock', 10, 2);
function add_warning_class_for_low_stock($classname, $item) {
$product = $item->get_product();
if ($product->get_stock_quantity() <= 5) { // 在庫が5以下の場合
$classname .= ' low-stock-warning';
}
return $classname;
}
このコードは在庫数が5以下の商品にlow-stock-warningクラスを追加します。
サンプルコード3: カスタムカテゴリーに基づくクラス追加
add_filter('woocommerce_order_item_class', 'add_category_class_to_order_item', 10, 2);
function add_category_class_to_order_item($classname, $item) {
$product = $item->get_product();
if (has_term('special-category', 'product_cat', $product->get_id())) {
$classname .= ' special-category-class';
}
return $classname;
}
このコードは特定のカテゴリーに属する商品に、カスタムクラスを追加します。
サンプルコード4: 簡易的なカスタムスタイルの追加
add_filter('woocommerce_order_item_class', 'add_simple_style_class', 10, 2);
function add_simple_style_class($classname, $item) {
return $classname . ' simple-style';
}
このコードは、すべての注文アイテムにsimplestyleクラスを追加します。
サンプルコード5: 複数商品の場合のクラス追加
add_filter('woocommerce_order_item_class', 'add_multiple_items_class', 10, 2);
function add_multiple_items_class($classname, $item) {
if (WC()->cart->get_cart_contents_count() > 1) { // 複数の商品がある場合
$classname .= ' multiple-items';
}
return $classname;
}
このコードは、カートに複数の商品がある場合、multiple-itemsクラスを追加します。
この関数のアクションでの使用可能性
| アクション | 使用可能性 |
|---|---|
| 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 |