WooCommerce在产品 Headers 中显示产品类别

loading...


1

我有一个运行WooCommerce(版本2.3.8)的WordPress(4.2.2版)电子商务网站 .

在我的个人产品页面上,我希望设置产品的 Headers ,以包括我在WooCommerce中创建的自定义类别以及该产品所属的类别 .

我发现以下文件(wp-content / themes / mytheme / woocommerce / single-product / title.php)与单个产品的 Headers 相关,并按如下所示进行编辑,以尝试包含该产品所属的类别 . Headers 也是 .

使用下面的代码我设法显示类别,但问题是我显示所有类别,而不仅仅是该产品所属的类别 .

如何将返回的类别限制为仅限于产品所属的类别?

<?php
if ( ! defined( 'ABSPATH' ) ) 
    exit; // Exit if accessed directly
?>

<!-- Original Product Title START -->
<h1 itemprop="name" class="product-title entry-title">
    <?php the_title(); ?>
</h1>
<!-- Original Product Title END -->


<!-- New Product Title START -->
<h1 itemprop="name" class="product-title entry-title">
    <?php
        $taxonomy     = 'product_cat';
        $orderby      = 'name';  
        $show_count   = 0;      // 1 for yes, 0 for no
        $pad_counts   = 0;      // 1 for yes, 0 for no
        $hierarchical = 1;      // 1 for yes, 0 for no  
        $title        = '';  
        $empty        = 0;
        $args = array(
            'taxonomy'     => $taxonomy,
            'orderby'      => $orderby,
            'show_count'   => $show_count,
            'pad_counts'   => $pad_counts,
            'hierarchical' => $hierarchical,
            'title_li'     => $title,
            'hide_empty'   => $empty
        );
    ?>

    <?php 
        $all_categories = get_categories( $args );

        foreach ($all_categories as $cat) 
        {
            if($cat->category_parent == 0) 
            {
                $category_id = $cat->term_id;
    ?>      

    <?php       
        echo '
<a href="'. get_term_link($cat->slug, 'product_cat') .'">'. $cat->name .'</a>'; ?> <?php $args2 = array( 'taxonomy' => $taxonomy, 'child_of' => 0, 'parent' => $category_id, 'orderby' => $orderby, 'show_count' => $show_count, 'pad_counts' => $pad_counts, 'hierarchical' => $hierarchical, 'title_li' => $title, 'hide_empty' => $empty ); $sub_cats = get_categories( $args2 ); if($sub_cats) { foreach($sub_cats as $sub_category) { echo '
<a href="'. get_term_link($sub_category->slug, 'product_cat') .'">'. $sub_category->name .'</a>'; echo apply_filters( 'woocommerce_subcategory_count_html', ' <span class="cat-count">' . $sub_category->count . '</span>', $category ); } } ?> <?php } } ?> </h1> <!-- New Product Title END -->
2回答

  • 4

    您可以使用get_the_terms简单地将所有类别分配给产品

    $terms = get_the_terms( get_the_ID(), 'product_cat' );
    
    foreach ($terms as $term) {
    
        echo '<h1 itemprop="name" class="product-title entry-title">'.$term->name.'</h1>';
    }
    

  • 1

    使用 get_categories 函数检索类别名称: -

    您可以使用此代码显示产品类别名称 -

    <?php global $post, $product;
    $categ = $product->get_categories();
    echo $categ; ?>
    

loading...

评论

暂时没有评论!