如何在WordPress存档页面中获取相关类别

时间:2015-07-29 作者:Exclutips

我在WordPress中使用WooCommerce。我有几类这样的产品,

Example:

Product 1 Category (//parent)
-- Category 1
-- Category 2
-- Category 3
-- Category 4
Product 2 Category (//parent)
-- Category 10
-- Category 11
-- Category 12
-- Category 13
如果我在类别2(子)的存档页中,如何获取父类别(产品1类别)下的所有其他类别名称作为列表。

我在尝试什么

$args = array(
       \'hierarchical\' => 1,
       \'show_option_none\' => \'\',
       \'hide_empty\' => 0,
       \'parent\' => $parent_cat_ID,
       \'taxonomy\' => \'product_cat\'
   );
$subcats = get_categories($args);
echo \'<ul class="wooc_sclist">\';
foreach ($subcats as $sc) {
       $link = get_term_link( $sc->slug, $sc->taxonomy );
echo \'<li><a href="\'. $link .\'">\'.$sc->name.\'</a></li>\';
     }
echo \'</ul>\';
}

Out put should :

.Category 1
.Category 2
.Category 3
.Category 4
我使用了下面的代码,它在单个产品中运行良好。php页面-

<?php 
 $parent = get_category_parents( $cat, true, \' &raquo; \' ); 
echo $product->get_categories( \', \', \'<span>\' . _n( \'Category:\', \'Categories:\', sizeof( get_the_terms( $post->ID, \'product_cat\' ) ), \'woocommerce\' ) . \' \', \'.</span>\' ); 
?>

2 个回复
SO网友:Jurij Jazdanov

我通常通过从数据库获取数据来实现这一点

$result = mysql_query("SELECT * FROM wp_terms JOIN wp_term_taxonomy
ON wp_term_taxonomy.term_id = wp_terms.term_id 
WHERE wp_term_taxonomy.parent = ".$parent_cat_ID." 
AND wp_term_taxonomy.taxonomy = \'product_cat\'");

SO网友:Exclutips

我这样做是为了解决问题

  <?php 
    $terms = get_the_terms( $post->cat_ID , \'product_cat\' );
    foreach ($terms as $term) { 
        $term_id = $term->term_id;
        $term_link = get_term_link( $term, $taxonomy );
        $term_name = $term->name;
        echo \'<a class="cat-box" href="\' . $term_link . \'"><span class="cat-name">\' . $term_name . \'</span></a>\';   
    }
    ?>

结束