我想为产品存档页面上的类别添加一个自定义类,这样我就可以为类别标签添加自定义样式。
的例子:
-
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. 包装器- 等。
若要不应用此操作,请在if条件中使用
!
:// NOT if ( ! is_product_category() )..