概要
woocommerce_get_product_class_include_taxonomies フィルタは、WooCommerceの商品に関連するカスタムクラスを生成する際に使用されます。このフィルタを使用することで、商品クラスに特定のタクソノミー(分類)を含めることができ、デザインや表示をカスタマイズするのに役立ちます。具体的には、次のような機能を実装する際に頻繁に利用されます。
- 商品のカテゴリごとに異なるスタイルを適用する。
- 特定の製品タイプに基づいて動的なCSSクラスを追加する。
- ユーザーが選択したフィルタに応じて商品リストをカスタマイズする。
- 特定の製品属性に依存して異なるレイアウトを提供する。
- 商品体験を豊かにするために、新しいフィルタオプションを追加する。
- SNS共有リンクにおいて特定のCSSクラスを付与して見た目を調整する。
構文
add_filter('woocommerce_get_product_class_include_taxonomies', 'callback_function');
パラメータ
array $classes: 商品に関連するクラス名の配列。WC_Product $product: 現在の WooCommerce 商品オブジェクト。
戻り値
array: 商品に関連して追加されたクラス名の配列を返します。
使用可能なバージョン
- WooCommerceのバージョン: 2.1.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 |
サンプルコード
サンプルコード 1
add_filter('woocommerce_get_product_class_include_taxonomies', 'add_custom_product_class', 10, 2);
function add_custom_product_class($classes, $product) {
if (has_term('特定のカテゴリ', 'product_cat', $product->get_id())) {
$classes[] = 'custom-category-class';
}
return $classes;
}
説明: このコードは、特定のカテゴリに属する商品に custom-category-class というクラスを追加します。
サンプルコード 2
add_filter('woocommerce_get_product_class_include_taxonomies', 'include_custom_product_type_class', 10, 2);
function include_custom_product_type_class($classes, $product) {
if ($product->is_type('simple')) {
$classes[] = 'simple-product-class';
}
return $classes;
}
説明: この例では、シンプルな商品に simple-product-class というクラスを追加しています。
サンプルコード 3
add_filter('woocommerce_get_product_class_include_taxonomies', 'add_attribute_class_to_product', 10, 2);
function add_attribute_class_to_product($classes, $product) {
if ($product->get_attribute('サイズ') === 'L') {
$classes[] = 'size-large';
}
return $classes;
}
説明: このコードは、サイズ属性が ‘L’ の商品に size-large というクラスを付与します。
サンプルコード 4
add_filter('woocommerce_get_product_class_include_taxonomies', 'add_special_offer_class', 10, 2);
function add_special_offer_class($classes, $product) {
if ($product->get_sale_price()) {
$classes[] = 'on-sale';
}
return $classes;
}
説明: セール価格が設定されている商品に on-sale というクラスを追加しています。
サンプルコード 5
add_filter('woocommerce_get_product_class_include_taxonomies', 'customize_product_classes', 10, 2);
function customize_product_classes($classes, $product) {
$rating = $product->get_average_rating();
if ($rating >= 4) {
$classes[] = 'high-rated';
}
return $classes;
}
説明: 商品の平均評価が4以上の場合に high-rated というクラスが追加されます。