Search code examples
phpwordpresscategoriescustom-wordpress-pages

Wordpress how to remove parent category and keep only child categories with post titles


    <?php       
     $categories = get_categories( 
              array('
              hide_empty' => TRUE
              ) 
            );
            foreach($categories as $category) { ?>
            <?php
                $args=array(
                    'cat' => $category->term_id,
                    'post_type' => 'ourservices',
                    //'posts_per_page'  => 10,
                    //'category_name' => 'our-services', // replace it with your category slug
                    'orderby' => 'name',
                    'order' => 'ASC',
    
                );
    
                $the_query = new WP_Query( $args );
    
                if ( $the_query->have_posts() ) {
                    ?>
                       
                  <h2 class><?php echo $category->name; ?></h2>
                  <ul class="list-group list-group-flush">
                    <?php while ( $the_query->have_posts() ) { $the_query->the_post(); ?>
                       <li class="list-group-item"><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></li>
                    <?php }?>
                    </ul><br>
               <?php } 
                ?>
    
            <?php } 
            wp_reset_postdata();
?>

I tried with 'parent'=>0 but working with required result! enter image description here


Solution

  • You could use an if statement to check whether your parent category is the one you need to exclude.

    So your code would be something like this:

    $categories = get_categories(
      array(
        'hide_empty' => TRUE
      )
    );
    foreach ($categories as $category) { ?>
      <?php
      $args = array(
        'cat'       => $category->term_id,
        'post_type' => 'ourservices',
        'orderby'   => 'name',
        'order'     => 'ASC',
    
      );
    
      $the_query = new WP_Query($args);
    
      if ($the_query->have_posts()) {
        if ('Our Services' !== $category->name) {
      ?>
    
          <h2 class><?php echo $category->name; ?></h2>
          <ul class="list-group list-group-flush">
            <?php while ($the_query->have_posts()) {
              $the_query->the_post(); ?>
              <li class="list-group-item"><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></li>
            <?php } ?>
          </ul><br>
      <?php
        }
      }
      ?>
    <?php }
    wp_reset_postdata();