开发者

Wordpress if current category has children

Ok i have this Loop code:

<?php
    //get all categories then display all posts in each term
    $taxonomy = 'category';
    $p开发者_开发技巧aram_type = 'category__in';
    $term_args=array(
      'orderby' => 'name',
      'order' => 'ASC',
      'hide_empty' => 0,
      'hierarchical' => 0
    );
    $terms = get_terms($taxonomy,$term_args);
    if ($terms) {
      foreach( $terms as $term ) {
        $args=array(
          "$param_type" => array($term->term_id),
          'post_type' => 'products',
          'post_status' => 'publish'
          );
        $my_query = null;
        $my_query = new WP_Query($args);
        if( /*$my_query->have_posts()*/ 1==1 ) {  ?>
          <div id="<?php echo str_replace(" ","",$term->name); ?>" class="category section">
            <h3 class="categoryTitle"><?php echo $term->name;?></h3>
            <?php
          while ($my_query->have_posts()) : $my_query->the_post(); ?>
            <div class="product">
                <h3 class="productTitle"><?php the_title(); ?></h3>
                <div class="description"><?php the_content(); ?></div>
            </div>
            <div class="clearfix"></div>
           <?php
          endwhile;
          ?>
          </div>
     <?php
        }
      }
    }
    wp_reset_query();  // Restore global post data stomped by the_post().
    ?>      

What i need to do, is if the currently looped category has children then display all of the children names as H2's (or whatever really)? How can i do this?


I'd try the replacing your code with the following:

if ($terms) :

foreach( $terms as $term ) :

$args=array(
     "$param_type" => array($term->term_id),
     'post_type' => 'products',
     'post_status' => 'publish'
);

$children = get_posts($args);

if($children) : ?>

<div id="<?php echo str_replace(" ","",$term->name); ?>" class="category section">
     <h3 class="categoryTitle"><?php echo $term->name;?></h3>

     <?php foreach($children as $child) : setup_postdata($child); ?>

          <div class="product">
                <h3 class="productTitle"><?php the_title(); ?></h3>
                <div class="description"><?php the_content(); ?></div>
          </div>

     <?php endforeach; ?>

</div>


<?php endif; // if($children)

endforeach;

endif; // if($terms)

I've not tested this but it should put you in the right direction!

Hope it helps.


I had a same problem, but i think i have found a simply solution by checking the current post category has parent or not.

$term = get_queried_object();


if($term->post_parent != 0){
    echo 'has parent'; //this post category has child
}else{
    echo 'no parent'; //this post category doesn't have child
}

I hope this is helpful.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜