Wordpress - 列出每个类别下包含帖子的类别层次结构

时间:2012-01-31 02:59:38

标签: mysql database wordpress

在wordpress中,以下函数将回显一个类别列表,其中的帖子与每个类别名称下的每个类别相关联。

这样可以正常工作,除了这会产生扁平结构。一些类别是其他类别的子类别,我希望能够输出一个与此匹配的结构列表(类似于站点地图)

有人能够帮我弄清楚如何修改此代码来实现这个目标吗?

function posts_by_category() { 

 //get all categories then display all posts in each term
$taxonomy = 'category';
 $param_type = 'category__in';
 $term_args=array(
   'orderby' => 'name',
   'order' => 'ASC'
 );
 $terms = get_terms($taxonomy,$term_args);
 if ($terms) {
   foreach( $terms as $term ) {
     $args=array(
       "$param_type" => array($term->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 ''.$term->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(); ?></a></li>
               <?php  endwhile;  ?>
             </ul>
       </div>
     <?php
     }
   }
 }
 wp_reset_query();  // Restore global post data stomped by the_post().
 }

1 个答案:

答案 0 :(得分:1)

这是我前几天发现的代码段Hierarchical Category List with Post Titles,应该可以解决这个问题。

<?php
/*****************************************************************
*
* alchymyth 2011
* a hierarchical list of all categories, with linked post titles
*
******************************************************************/
// http://codex.wordpress.org/Function_Reference/get_categories

 foreach( get_categories('hide_empty=0') as $cat ) :
 if( !$cat->parent ) {
 echo '<ul><li><strong>' . $cat->name . '</strong></li>';
 process_cat_tree( $cat->term_id );
 }
 endforeach;

 wp_reset_query(); //to reset all trouble done to the original query
//
function process_cat_tree( $cat ) {

 $args = array('category__in' => array( $cat ), 'numberposts' => -1);
 $cat_posts = get_posts( $args );

 if( $cat_posts ) :
 foreach( $cat_posts as $post ) :
 echo '<li>';
 echo '<a href="' . get_permalink( $post->ID ) . '">' . $post->post_title . '</a>';
 echo '</li>';
 endforeach;
 endif;

 $next = get_categories('hide_empty=0&parent=' . $cat);

 if( $next ) :
 foreach( $next as $cat ) :
 echo '<ul><li><strong>' . $cat->name . '</strong></li>';
 process_cat_tree( $cat->term_id );
 endforeach;
 endif;

 echo '</ul>';
}
?>