当前位置:首页原创文章wordpress获取分类下文章列表四种方法

wordpress获取分类下文章列表四种方法

以下代码实际上使用query_posts()函数调取分类目录下的文章,showposts是调取的数量。

<?php
    $cats = get_categories();
    foreach ( $cats as $cat ) {
    query_posts( 'showposts=10&cat=' . $cat->cat_ID );
?>
    <h3><?php echo $cat->cat_name; ?></h3>
    <ul class="sitemap-list">
        <?php while ( have_posts() ) { the_post(); ?>
        <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
        <?php } wp_reset_query(); ?>
    </ul>
<?php } ?>

在官方文档中,这样强调:“如果我们不得不用到query_posts(),必须确保每次使用query_posts()后同时执行wp_reset_query();”。这就是为什么在上面的代码中加上了wp_reset_query()的原因。

修改其中的数字10可以设定显示的篇数,可用于在单页面上显示全部分类文章。

二、使用get_posts()函数

只需通过get_posts来获取分类ID就可以输出分类下的文章,以及通过numberposts来控制文章显示的数量。

<?php $posts = get_posts( "category=4&numberposts=10" ); ?>  
<?php if( $posts ) : ?>  
<ul><?php foreach( $posts as $post ) : setup_postdata( $post ); ?>  
<li>  
<a href=”<?php the_permalink() ?>” rel=”bookmark” title=”<?php the_title(); ?>”><?php the_title(); ?></a>  
</li>  
<?php endforeach; ?>  
</ul>  
<?php endif; ?>

三、结合wp_list_categories()函数输出分类标题

<h2> <?php wp_list_categories('include=11&title_li=&style=none'); ?> </h2>
      <!--//输出 ID 为11的分类的标题 -->
         <?php  echo category_description(11); ?>
      <!--//输出 ID 为11的分类的描述 -->
          <?php query_posts('showposts=10&cat=11'); ?>
      <!-- //query_posts 给 The Loop 限定的条件是:显示12篇日志和分类 ID 为11 -->
           <?php while (have_posts()) : the_post(); ?>
      <!--//The Loop 开始 -->
     <li>
      <a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title(); ?>"><? echo wp_trim_words( get_the_title(),24 ); ?></a>
       <?php  the_time('m/d'); ?>
     </li>
      <!-- //用列表的方式输出带有链接的文章标题-->
            <?php endwhile;wp_reset_query(); ?>
      <!--//The Loop 结束 -->

四、自定义函数

1、我们自定义一个函数popularPosts()

function popularPosts($num) {  
    global $wpdb;  
      
    $posts = $wpdb->get_results("SELECT comment_count, ID, post_title FROM $wpdb->posts ORDER BY comment_count DESC LIMIT 0 , $num");  
      
    foreach ($posts as $post) {  
        setup_postdata($post);  
        $id = $post->ID;  
        $title = $post->post_title;  
        $count = $post->comment_count;  
        if ($count != 0) {  
            $popular .= '<li>';  
            $popular .= '<a href="' . get_permalink($id) . '" title="' . $title . '">' . $title . '</a> ';  
            $popular .= '</li>';  
        }  
    }  
    return $popular;  
}

这里使用get_results()查询了数据库,相对速度快一点。
2、调用函数 popularPosts(10) 显示10篇文章。

<div class="popular">  
    <h2>Most Popular Posts</h2>  
    <ul>  
        <?php echo popularPosts(10); ?>  
    </ul>  
</div>

给TA打赏
共{{data.count}}人
人已打赏
原创文章

WordPress忘记后台密码,重置登录密码方法

2022-11-29 21:26:04

原创文章子主题类

子主题视屏缩略图效果演示

2023-3-9 14:43:12

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
购物车
优惠劵
有新私信 私信列表
搜索