如何在列表中按层次顺序显示具有自定义分类法(产品类别)的自定义帖子类型的产品?
我想按以下顺序购买:
h3.parentcategory 1
-h4.childcategory 1
-li.product of childcategory 1
-li.product of childcategory 1
-h4.childcategory 2
-li.product of childcategory 2
-li.product of childcategory 2
h3.parentcategory 2
-h4.childcategory 1 of parent 2
不幸的是,我不能在第二级(儿童类别1和2)上下功夫。我使用此代码显示类别和产品:
$custom_terms = get_terms( \'productcategory\' );
foreach ( $custom_terms as $custom_term ) {
wp_reset_query();
$args = array(
\'post_type\' => \'product\',
\'tax_query\' => array(
array(
\'taxonomy\' => \'productcategories\',
\'field\' => \'slug\',
\'terms\' => $custom_term->slug,
\'orderby\' => \'term_group\',
),
),
);
$loop = new WP_Query( $args );
if ( $loop->have_posts() ) {
echo \'<h3>\' . $custom_term->name . \'</h2>\';
while ( $loop->have_posts() ) : $loop->the_post();
get_the_title();
endwhile;
}
}
我需要帮助找出这个列表的嵌套级别。
我编辑这篇文章是为了澄清:感谢大家的帮助。很抱歉我在发帖时是个无赖。。。
我想做的是列出属于子类别的产品,这些子类别可以是一个大家族(Maincategory)的一部分。我试图将子类别归为一个主类别
vegetables (Main)
-tomatoes (sub)
-red tomatoe sweet (product)
-pink tomatoe sour (product)
-cucumber (sub)
-some kind of cucumber(product)
fruits (Main)
-apple(sub)
-sweet apple (product)
-Golden delicious (product)
最合适的回答,由SO网友:darrinb 整理而成
尝试以下操作:
<?php
$parent_terms = get_terms(
\'name_of_your_taxonomy\',
array(
\'parent\' => 0,
)
);
foreach ( $parent_terms as $parent_term ) {
$child_terms = get_terms(
\'name_of_your_taxonomy\'
array(
\'child_of\' => $parent_term->term_id,
)
);
foreach ( $child_terms as $child_term ) {
$args = array(
\'post_type\' => \'product\',
\'tax_query\' => array(
array(
\'taxonomy\' => \'name_of_your_taxonomy\',
\'field\' => \'slug\',
\'terms\' => $child_term->slug,
),
),
);
$loop = new WP_Query($args);
if ( $loop->have_posts() ) :
while ( $loop->have_posts() ) :
$loop->the_post();
echo \'<h3>\' . $parent_term->name . \'</h3>\';
echo \'<h4>\' . $parent_term->name . \'</h4>\';
echo get_the_title();
endwhile;
wp_reset_postdata();
endif;
}
}
基本上,您所做的是:
获取所有父术语循环浏览父术语并获取每个术语的子术语循环浏览儿童术语并获取与儿童相关的帖子