您现在的位置是:首页 > 网站制作 > WordpressWordpress

WordPress使用query_posts()函数WP_Query类获取指定分类中的日志

杰帅2023-06-26【Wordpress】人已围观

简介wordpress 获取指定分类中的日志列表常常用于显示指定分类下的日志,适合于CMS,或者网站地图之类的,我们常用的函数是query_posts()函数,使用WP_Query类也有更多的优点。

wordpress 获取指定分类中的日志列表常常用于显示指定分类下的日志,适合于CMS,或者网站地图之类的,我们常用的函数是query_posts()函数,使用WP_Query类也有更多的优点。

1.利用query_posts()函数

query_posts()是wordpress用来显示内容的最容易的方法之一,它可以通过各种灵活的方式检索或过滤你所需要的内容。

$args = 'cat=61&posts_per_page=10'; 
query_posts( $args ); 
while ( have_posts() ) : the_post();
    echo '<li>';
    the_title();
    echo '</li>';
endwhile; 
wp_reset_query();

query_posts函数虽好用,但在使用该函数时,我们仍需要注意和尽量减少使用该函数的频率。同时,在官方文档中,这样强调:“如果我们不得不用到query_posts(),必须确保每次使用query_posts()后同时执行wp_reset_query();”。这就是为什么我在上面的代码中加上了wp_reset_query()的原因。

另外,大多数使用wordpress的朋友们,可能都对wp-pagenavi这个插件不再陌生。这是作为辅助分页的插件成为很多wper的常用工具之一。其作者在自己的博客中,分析并强调了部分朋友在分页时会出现数据差异情况的原因,并提出了正确使用query_posts()函数的方法。

综合以上几点,加上易维护性的目的,我们重新来理一下代码:

    $args = array(
        'cat'   => 61,
        'posts_per_page'    => 10,
        'paged'             => get_query_var('page') //如果需要分页,则加上这一句
    );    
    query_posts( $args ); 
    while ( have_posts() ) : the_post();
        echo '<li>';
        the_title();
        echo '</li>';
    endwhile;  
    wp_reset_query();

2.WP_Query类

WP_Query类被设定用来处理wordpress众多复杂的数据库处理,未来一段时间都将被提倡的使用方法之一。按我个人的习惯和对wordpress的浅显认识,建议放弃烂用query_posts(),而改用WP_Query().尽管看上去有一点点烦。

$args = array(
        'cat'   => 61,
        'posts_per_page'    => 10,
    ); 
    $tech = new WP_Query( $args ); 
    if ( $tech -> have_posts() ) {    
        while ( $tech -> have_posts() ) : $tech ->the_post();
            echo '<li>';
            the_title();
            echo '</li>';
        endwhile; 
    }else {
        echo 'no posts in current category!';
    }

这样独立来调用数据,即安全易维护,又比较明晰;

以上两种方式中,$args所具有的内定参数,包括category__in, category__not_in, post__in, post__not_in等等可以至官方文档,作进一步了解:http://codex.wordpress.org/Class_Reference/WP_Query#Parameters

参考:

http://fairyfish.net/m/how-to-display-posts-from-a-certain-category/

http://codex.wordpress.org/Function_Reference/query_posts

http://codex.wordpress.org/Class_Reference/WP_Query#Parameters

http://scribu.net/wordpress/wp-pagenavi/right-way-to-use-query_posts.html

http://wp.smashingmagazine.com/2011/09/21/interacting-with-the-wordpress-database/

http://www.wordpress.la/query_posts_tips

http://jokerliang.com/

Tags:query_posts()   wordpress教程   WP_Query类

很赞哦! ()

文章评论

本站推荐

站点信息

  • 建站时间:2018-10-24
  • 网站程序:帝国CMS7.5
  • 主题模板《今夕何夕》
  • 文章统计1172篇文章
  • 标签管理标签云
  • 统计数据百度统计
  • 微信公众号:扫描二维码,关注我们