Wordpress 如何删除 parent 类别并仅保留具有 post 标题的 child 类别

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();
?>

我尝试使用 'parent'=>0,但得到了所需的结果!

您可以使用 if statement 检查您的父类别是否是您需要排除的类别。

所以你的代码应该是这样的:

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