【问题标题】:Wordpress - is get_posts() more efficient than The Loop?Wordpress - get_posts() 比循环更有效吗?
【发布时间】:2013-11-27 07:56:52
【问题描述】:

category.php,我想获取该类别的帖子列表。

我找到了两种方法:使用get_posts($args)The Loop

get_posts()方式

$args = array (
  "category" => ID );
$posts = get_posts($args);
// then use foreach to loop the $posts

循环方式

<?php if (have_posts() ): ?>
  <?php while (have_posts() ): the_post(); ?>
    ...
  <?php endwhile; ?>
<?php endif; ?>

那么哪个更高效?

根据我在搜索中的发现,get_posts() 用于自定义模板,而The Loop 在遵循 Wordpress 命名约定的模板中使用。

我更喜欢 get_posts(),但如果与 The Loop 相比开销很大,我应该重新考虑一下。

【问题讨论】:

    标签: php wordpress loops wordpress-theming


    【解决方案1】:

    我终于找到了答案。

    当我们使用正确的模板(遵循命名约定的模板)打开页面时,Wordpress 会自动进行查询以获取所有相关的帖子或内容

    所以如果我使用$posts = get_posts($args);,这意味着我做了额外的查询,这是不必要的。

    $posts = get_posts($args); 只能在模板之外使用,例如在 侧边栏 上始终存在于每个页面上。

    【讨论】:

      猜你喜欢
      • 2016-04-15
      • 1970-01-01
      • 2012-07-18
      • 2012-01-31
      • 1970-01-01
      • 2019-03-21
      • 1970-01-01
      • 2019-08-24
      • 1970-01-01
      相关资源
      最近更新 更多