I amusing wordpress and have setup a custom post type (called products & custom taxonomy called product_category) and I want to do the follow
I will have a page called catalog and want to display all the categories/sub categories and products under the sub categories on one page.
However am unsure on the code to to it.
Get all categories and echo the title, for each parent category with children echo the sub categories and then products else just echo the parent category and the products.
Category 1 (echo parent stuff) Sub category 1 (echo Sub category stuff) Post 1 (echo post stuff) Post 2 Sub category 2 Post 1 Post 2
Category 2 Sub category 1 Post 1 Post 2
Category 3 Sub category 1 Post 1 Post 2
This code should work for you.
$top_level_terms = get_terms( 'product_cat', array( 'parent' => 0 ) );
foreach( $top_level_terms as $top_term )
{
$child_terms = get_terms( 'product_cat', array( 'child_of' => $top_term->term_id ));
//Parent Category Name
echo '<b>'.$top_term->name .'</b><br>';
$top_id=$top_term->term_id;
if(count($child_terms)>0)
{
foreach ( $child_terms as $child_term )
{
$id=$child_term->term_id;
//Child category name
echo '<b>=>' .$child_term->name .'</b><br>';
$myposts=get_posts(array(
'post_type' => 'product',
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'term_id',
'terms' => $id)
))
);
echo '<ul>';
foreach ($myposts as $mypost) {
//Posts
echo '<li>'.$mypost->post_title.'</li>' ;
}echo '</ul>';
wp_reset_postdata();
}
}
else
{
$myposts=get_posts(array(
'post_type' => 'product',
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'term_id',
'terms' => $top_id)
))
);echo '<ul>';
foreach ($myposts as $mypost) {
echo '<li>'.$mypost->post_title.'</li>' ;
}
echo '</ul>';
wp_reset_postdata();
}
}
If you have any issues let me know
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.