9

我是 Wordpress 的新手,一直在努力创建一个类别循环。循环应该:

  1. 遍历所有类别
  2. 回显类别名称(带有链接到
  3. 回显该类别中的最后 5 个帖子(带有帖子的永久链接)

每个的 html 将是

<div class="cat_wrap">
   <div class="cat_name">
       <a href="<?php get_category_link( $category_id ); ?>">Cat Name</a>
   </div>
   <ul class="cat_items">
      <li class="cat_item">
         <a href="permalink">cat item 1</a>
      </li>
      <li class="cat_item">
         <a href="permalink">cat item 2</a>
      </li>
      <li class="cat_item">
          <a href="permalink">cat item 3</a>
      </li>
      <li class="cat_item">
         <a href="permalink">cat item 4</a>
      </li>
      <li class="cat_item">
         <a href="permalink">cat item 5</a>
      </li>
   </ul>
</div>

请帮忙

4

4 回答 4

12

糟糕,错过了您想要 5 个帖子

<?php
//for each category, show 5 posts
$cat_args=array(
  'orderby' => 'name',
  'order' => 'ASC'
   );
$categories=get_categories($cat_args);
  foreach($categories as $category) { 
    $args=array(
      'showposts' => 5,
      'category__in' => array($category->term_id),
      'caller_get_posts'=>1
    );
    $posts=get_posts($args);
      if ($posts) {
        echo '<p>Category: <a href="' . get_category_link( $category->term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $category->name ) . '" ' . '>' . $category->name.'</a> </p> ';
        foreach($posts as $post) {
          setup_postdata($post); ?>
          <p><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></p>
          <?php
        } // foreach($posts
      } // if ($posts
    } // foreach($categories
?>
于 2009-11-24T12:55:58.177 回答
6

在这里保持简单是您如何解决它的方法

<?php wp_list_categories('show_count=1&title_li=<h2>Categories</h2>'); ?>
于 2009-11-22T23:40:52.703 回答
2

我已经制作了这段代码来循环嵌套类别。分享。

        //Start on the category of your choice       
        ShowCategories(0);

        function ShowCategories($parent_category) {
                $categories = get_categories(array('parent' => $parent_category, 'hide_empty' => 0));  
                foreach ($categories as $category) {
                    ?><ul><li><?=$category->cat_name;?><?
                    ShowCategories($category->cat_ID);
                    ?></li></ul><?
                }
        }
于 2014-01-25T15:38:49.040 回答
0

看看另一个 Stackoverflow 线程:

https://wordpress.stackexchange.com/questions/346/loop-through-custom-taxonomies-and-display-posts/233948#233948

我发布了一个我在生产中使用的答案,并且就像一个魅力。

请记住调整参数以仅显示 5 个帖子,而不是全部。

$args = array( 'showposts' => 5 );

将 'showposts' => 5 添加到循环中的当前参数数组,该循环遍历每个类别的帖子。

于 2016-08-03T18:32:59.807 回答