Wordpress如果当前类别有孩子

时间:2011-10-09 21:56:36

标签: wordpress

好的,我有这个循环代码:

<?php
    //get all categories then display all posts in each term
    $taxonomy = 'category';
    $param_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().
    ?>      

我需要做的是,如果当前循环类别有子项,那么将所有子项名称显示为H2(或者其他什么)?我怎么能这样做?

2 个答案:

答案 0 :(得分:1)

我尝试用以下内容替换您的代码:

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)

我没有对此进行测试,但它应该让你朝着正确的方向前进!

希望它有所帮助。

答案 1 :(得分:0)

我遇到了同样的问题,但我认为通过检查当前的帖子类别是否为父母,我找到了一个简单的解决方案。

$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
}

我希望这有用。