繁体   English   中英

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

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

我在用wordpress并设置了一个自定义帖子类型(称为产品和自定义分类法,称为product_category),我想执行以下操作

我将有一个称为目录的页面,并希望在一页上显示所有子类别/子类别和产品。

但是,不确定对其的代码。

获取所有类别并回显标题,对于带有子级的每个父类别,先回显子类别,然后再回响产品,否则回显父类别和产品。

类别1(回显父级内容)子类别1(回显子级内容)帖子1(回声后级内容)帖子2子类别2帖子1帖子2

类别2子类别1帖子1帖子2

类别3子类别1帖子1帖子2

此代码应为您工作。

$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();
    }


}

如果您有任何问题,请通知我

暂无
暂无

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

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