在Woocommerce中为产品类别存档页面添加正文类

问题描述 投票:1回答:4

我想在产品类别归档页面的body类中添加产品类别slug。

以下是我想要的示例(产品类别页面示例的网址): https://example.com/product-category/canon/ ...所以我想在体型课中选择“佳能”。

php wordpress woocommerce custom-taxonomy hook-wordpress
4个回答
2
投票

您的示例链接似乎不起作用;但是,WooCommerce应该已经在您的类别页面中添加了一个特定于术语的类:从archive tax-product_cat term-{slug} term-{id}到产品类别页面。以您的示例链接为例,假设术语ID为7(例如),正文类将包括:

tax-product_cat term-7 term-canon

因此,如果您需要通过CSS / jQuery /其他方式访问它,您可以使用选择器body.term-canon


0
投票

您可以在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' );

0
投票

为此,您需要在激活的主题中的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。


0
投票

即使Woocommerce嵌入作为身体类产品类别术语slug为term-canon,您可以使用专用的WordPress canon动作钩,使用Woocommerce body_class条件函数和WordPress 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;
}

代码位于活动子主题(或活动主题)的function.php文件中。经过测试和工作。

© www.soinside.com 2019 - 2024. All rights reserved.