php – 创建自己的WordPress循环的最佳方法是什么?

似乎有三种主要方法可以使用其内置函数wordpress输出内容,推荐使用WP_Query:

> WP_Query
> query_posts
> get_posts

它们之间有什么区别? (我知道WP_Query是类,其他两个是方法).

在同一页面上拥有多个循环的最简洁方法是什么,它们之间没有任何干扰?

我正在寻找你如何编程WP循环的例子;
例如按类别输出2个单独的帖子列表,附件,元数据等

这是我到目前为止找到的最佳参考:

> Define Your Own WordPress Loop Using WP_Query

我已经使用了WP_Query和get_posts.在我的一个侧边栏模板中,我使用以下循环来显示特定类别的帖子,方法是使用带有“category_to_load”键的自定义字段,其中包含类别slug或类别名称.真正的区别在于任何一种方法的实施.

get_posts方法在我的一些模板中看起来像这样:

<?PHP    
    global $post;
    $blog_posts = get_posts($q_string);
    foreach($blog_posts as $post) : 
    setup_postdata($post);
?>
           <div class="blog_post">
             <div class="title">
               <h2><a href="<?PHP the_permalink(); ?>"><?PHP the_title(); ?></a></h2>
               <span class="date"><?PHP the_time('F j,Y'); ?> by <?PHP the_author(); ?></span>
             </div>
             <?PHP the_excerpt(); ?>
           </div>
     <?PHP endforeach; ?>

WP_Query实现如下所示:

$blog_posts = new WP_Query('showposts=15');

while ($blog_posts->have_posts()) : $blog_posts->the_post(); ?>

            <div <?PHP post_class() ?> id="post-<?PHP the_ID(); ?>" class="blog_post">
                <div class="title">
                  <h2><a href="<?PHP the_permalink() ?>" rel="bookmark" title="Permanent Link to <?PHP the_title_attribute(); ?>"><?PHP the_title(); ?></a></h2>
                  <span class="date"><?PHP the_time('F jS,Y') ?> <!-- by <?PHP the_author() ?> --></span>
                </div>
                <div class="entry">
                    <?PHP the_content(); ?>
                </div>
                <p class="postMetadata"><?PHP the_tags('Tags: ',','<br />'); ?> Posted in <?PHP the_category(',') ?> | <?PHP edit_post_link('Edit','',' | '); ?>  <?PHP comments_popup_link('No Comments &#187;','1 Comment &#187;','% Comments &#187;'); ?></p>
            </div>

        <?PHP endwhile; ?>

主要区别在于您不必重置全局$post变量,并且在使用WP_query时也不必通过在每个post对象上调用setup_postdata($post)来设置post数据.您还可以在WP_Query函数上使用可爱的have_posts()函数,这在get_posts()中是不可用的.

你不应该使用query_posts()函数,除非你真的想要,因为它修改页面的主循环.请参阅docs.因此,如果您要构建一个特殊页面显示您的博客,那么调用query_posts可能会弄乱页面的循环,因此您应该使用WP_Query.

那只是我的两分钱.我的最终建议,你的第一选择应该是WP_Query.

-克里斯

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...