我想在产品类别存档页面的正文类中添加产品类别 slug。
这是我想要的示例(产品类别页面示例的 url):
https://example.com/product-category/canon/
……所以我想在 body 类中使用“canon”。
我想在产品类别存档页面的正文类中添加产品类别 slug。
这是我想要的示例(产品类别页面示例的 url):
https://example.com/product-category/canon/
……所以我想在 body 类中使用“canon”。
您的示例链接似乎不起作用;但是,WooCommerce 应该已经在您的类别页面中添加了一个特定于术语的类:类似于archive tax-product_cat term-{slug} term-{id}
产品类别页面的内容。以您的示例链接为例,假设术语 ID 是7
(例如),正文类将包括:
tax-product_cat term-7 term-canon
所以如果你需要通过 CSS/jQuery/whatever 访问它,你可以使用 selector body.term-canon
。
即使 Woocommerce将产品类别术语 slug 作为 body 类嵌入term-canon
,您也可以使用专用的 WordPress动作挂钩轻松添加canon
,使用 Woocommerce条件函数和 WordPress这样的方式:body_class
is_product_category()
get_queried_object()
add_filter( 'body_class', 'product_category_slug_to_body_class', 99, 1 );
function product_category_slug_to_body_class( $classes ){
if( is_product_category() ){
$classes[] = get_queried_object()->slug;
}
return $classes;
}
代码在您的活动子主题(或活动主题)的functions.php 文件中。测试和工作。
为此,您需要在您激活的主题中的 functions.php 文件中添加以下代码。
add_filter( 'body_class', 'product_cats_css_body_class' );
function product_cats_css_body_class( $classes ){
if( is_archive( 'product-cat' ) )
{
$custom_terms = get_the_terms(0, 'product_cat');
if ($custom_terms) {
foreach ($custom_terms as $custom_term) {
$classes[] = $custom_term->slug;
}
}
}
return $classes;
}
这将在 body 类的最后添加类别 slug。
您可以在 body 类中使用 page slug,请参阅此代码
function add_slug_body_class( $classes ) {
global $post;
if ( isset( $post ) ) {
$classes[] = $post->post_type . '-' . $post->post_name;
}
return $classes;
}
add_filter( 'body_class', 'add_slug_body_class' );