簡體   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