简体   繁体   English

如何在页面上回显类别,子类别以及子类别中的帖子?

[英]How can I echo the categories, sub categories and then posts within the sub categories all on one page?

I amusing wordpress and have setup a custom post type (called products & custom taxonomy called product_category) and I want to do the follow 我在用wordpress并设置了一个自定义帖子类型(称为产品和自定义分类法,称为product_category),我想执行以下操作

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 类别1(回显父级内容)子类别1(回显子级内容)帖子1(回声后级内容)帖子2子类别2帖子1帖子2

Category 2 Sub category 1 Post 1 Post 2 类别2子类别1帖子1帖子2

Category 3 Sub category 1 Post 1 Post 2 类别3子类别1帖子1帖子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 如果您有任何问题,请通知我

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM