WordPress使用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 '
  • '; the_title(); echo '
  • '; 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 '
  • '; the_title(); echo '
  • '; 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 '
  • '; the_title(); echo '
  • '; 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/

    文章来源于互联网

    © 版权声明
    THE END
    喜欢就支持一下吧
    点赞32 分享
    评论 抢沙发
    头像
    欢迎您留下宝贵的见解!
    提交
    头像

    昵称

    取消
    昵称表情代码图片

      暂无评论内容