wordpress - 在 WooCommerce 档案页面上添加带有产品类别 ID 的额外类
问题描述
我想在产品存档页面上的类别中添加一个自定义类,以便我可以将自定义样式添加到类别标签中。
例子:
类别 1 中的产品 X --> 黄色类别标签
类别 2 中的产品 Y --> 红色类别标签
我正在使用这个 php 片段,但这是针对单个产品页面并应用于<body>
元素的。如何将其更改为也适用于商店存档页面?
add_filter( 'body_class','my_body_classes2' );
function my_body_classes2( $classes ) {
if ( is_product() ) {
global $post;
$terms = get_the_terms( $post->ID, 'product_cat' );
foreach ($terms as $term) {
$product_cat_id = $term->term_id;
$classes[] = 'product-in-cat-' . $product_cat_id;
}
}
return $classes;
}
解决方案
您可以使用较新的woocommerce_post_class
过滤器挂钩
所以你得到:
/**
* WooCommerce Post Class filter.
*
* @since 3.6.2
* @param array $classes Array of CSS classes.
* @param WC_Product $product Product object.
*/
function filter_woocommerce_post_class( $classes, $product ) {
// Returns true when viewing a product category archive.
// Returns true when on the product archive page (shop).
if ( is_product_category() || is_shop() ) {
// Set taxonmy
$taxonomy = 'product_cat';
// Get the terms
$terms = get_the_terms( $product->get_id(), $taxonomy );
// Error or empty
if ( is_wp_error( $terms ) || empty( $terms ) ) {
return $classes;
}
// Loop trough
foreach ( $terms as $index => $term ) {
// Product term Id
$term_id = $term->term_id;
// Add new class
$classes[] = 'product-in-cat-' . $term_id;
}
}
return $classes;
}
add_filter( 'woocommerce_post_class', 'filter_woocommerce_post_class', 10, 2 );
注意: if 条件可以用其他条件标签扩展/约束
例子:
is_product()
- 在单个产品页面上返回 true。is_singular 的包装器。- ETC..
要不应用此功能,
!
请在 if 条件中使用:// NOT if ( ! is_product_category() )..
推荐阅读
- odata - SAPUI5 在使用 odata v4 初始化时动态过滤表
- javascript - Web-NFC:如何在我的 html5 页面中使用 web-nfc
- r - search_30day() 和 search_premium() 函数的 rtweet 包中的“max_id”错误
- laravel - 想集成 Shiprocket APi 在 PHP/Laravel 中创建自定义订单
- r - R循环构造根据前后信息行查找当前行
- google-colaboratory - 在google colab中打开笔记本时出现api问题
- powershell - Powershell 将环境变量设置为 $false 导致奇怪的行为
- python - 我想当我输入搜索词时,它会搜索所有网站和浏览器并显示结果
- python - 正确答案后如何停止(PYTHON)
- python - 如何使用 Opencv 从一个 rtsp Url 逐个视频捕获视频?