2016-11-15 4 views
0

親カテゴリタイトル、サブカテゴリタイトル、および各サブカテゴリのすべての投稿を表示するカテゴリテンプレートを作成したいと考えています。Wordpress Template - 親カテゴリのすべての投稿をサブカテゴリで区切って表示する

だから、この

親 サブカテゴリ ポスト#1 ポスト#2 サブカテゴリ ポスト#3 ポスト#ここで4

ようになり、私がこれまで持っているものですが、私はこだわっていますどのように前進するか。お使いのカテゴリテンプレート内

function display_category_posts($cat_id) { 
    echo get_cat_name($cat_id); 
    $the_query = new WP_Query(array('cat' => $cat_id)); 
    // you loop code 
    wp_reset_query(); //or wp_reset_postdata(), not put it in have_posts() block, we should always reset query even there no posts found. 
} 

あなたのテーマのfunctions.phpで

<?php if (have_posts()) : ?> 

      <div class="section-header"> 
       <h1 class="page-title"><?php single_cat_title(''); ?></h1> 
       <!-- <?php 
        the_archive_title('<h1 class="page-title">', '</h1>'); 
        the_archive_description('<div class="taxonomy-description">', '</div>'); 
       ?> --> 
      </header><!-- .page-header --> 
      <p>Some text</p> 

       <?php 

        // The Query 
        $the_query = new WP_Query(array('cat' => 72)); 

        // The Loop 
        if ($the_query->have_posts()) { 
         echo '<ul>'; 
         while ($the_query->have_posts()) { 
          $the_query->the_post(); 
          echo '<li>' . get_the_title() . '</li>'; 
         } 
         echo '</ul>'; 
         /* Restore original Post Data */ 
         wp_reset_postdata(); 
        } else { 
        // no posts found 
        } 

        ?> 


     <?php else : ?> 

      <?php ?> 

     <?php endif; ?> 

答えて

1

// get current category of viewing page. 
$current_cat_obj = get_queried_object(); 

// try to get sub categories. 
$sub_cat_ids = get_terms('category', array(
    'parent' => $current_cat_obj->term_id, 
    'hide_empty' => false, 
    'fields' => 'ids' 
)); 

// if the category of current page is a top-level category and has sub categories, display is as sub category posts view. 
if(!$current_cat_obj->parent && !empty($sub_cat_ids)) { 
    foreach($sub_cat_ids as $sub_cat_id) { 
     display_category_posts($sub_cat_id); 
    } 
} else { 
    // otherwise, display it as normal category view. 
} 
+0

ありがとうございましたが、これは私に次のようなエラー「警告を与える:不正がISSETかに空にタイプをオフセット/homepages/9/d389995387/htdocs/marketsquaresj/wp-includes/class-wp-term-query.php on line 376「私が提供したコードにカテゴリテンプレートコードを挿入する場所を教えてください再現する何か? – user1488639

+0

申し訳ありませんが、私の間違いです。 'object_id'でなく、' object'でなければなりません。コードを更新して、もう一度やり直してください。 – Cl0udSt0ne

+0

それは感謝したそれはありがとう! – user1488639

関連する問題