WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] how to show parent categories and subcategories with posts? (3 posts)

  1. saintxiao
    Member
    Posted 2 years ago #

    hi, is there possible to show format like blow?
    parent category 1
    >>subcategory 1
    >>post 1
    >>post 2
    >>subcategory 2
    >>post 1
    >>post 2
    parent category 2
    >>subcategory 1
    >>post 1
    >>post 2
    >>subcategory 2
    >>post 1
    >>post 2

  2. Gaurav Raghav
    Member
    Posted 2 years ago #

    Yes there are plugins available . Search in plugin directory " menu hierachy " or else create a menu and put categories and sub categories you wanted to show there .

  3. saintxiao
    Member
    Posted 2 years ago #

    thanks for reply, i already solve it myself. here is my code this only work for two level categories.

    <?php
    //get all categories then display all posts in each term
    $taxonomy = 'category'; //change this name if you have taxonomy
    $param_type = 'category__in';
    $term_args=array(
      'orderby' => 'name',
      'order' => 'ASC'
    );
    $terms = get_terms($taxonomy,$term_args);
    if ($terms) {
    
    	foreach($terms as $term){ //this foreach is for top level
    		if($term->parent == 0){
    		echo '<h2>'.$term->name.'</h2>'; //get top level category name
    $term_args=array(
      'orderby' => 'name',
      'order' => 'ASC',
      'child_of' => $term->term_id
    );
    $termss = get_terms($taxonomy,$term_args);
      foreach( $termss as $terms ) { //this foreach is for second level
        $args=array(
          "$param_type" => array($terms->term_id),
          'post_type' => 'post',
          'post_status' => 'publish',
          'posts_per_page' => -1,
          'caller_get_posts'=> 1
          );
        $my_query = null;
        $my_query = new WP_Query($args);
        if( $my_query->have_posts() ) {  ?>
          <div class="category section">
            <h3><?php echo 'Category '.$terms->name; //get second level category name?></h3>
            <ul>
            <?php
          while ($my_query->have_posts()) : $my_query->the_post(); ?>
            <li><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); //get posts title name?></a></li>
           <?php
          endwhile;
          ?>
          </ul>
          </div>
     <?php
        }}
      }
      }
    }
    wp_reset_query();  // Restore global post data stomped by the_post().
    ?>

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags

No tags yet.