Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/243.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php Wordpress-get_posts()比循环更有效吗?_Php_Wordpress_Loops_Wordpress Theming - Fatal编程技术网

Php Wordpress-get_posts()比循环更有效吗?

Php Wordpress-get_posts()比循环更有效吗?,php,wordpress,loops,wordpress-theming,Php,Wordpress,Loops,Wordpress Theming,在category.php中,我想获得该类别中的帖子列表 我找到了两种方法:使用get_posts($args)和循环 获取帖子()方式 $args = array ( "category" => ID ); $posts = get_posts($args); // then use foreach to loop the $posts <?php if (have_posts() ): ?> <?php while (have_posts() ): the_

category.php
中,我想获得该类别中的帖子列表

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

获取帖子()方式

$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; ?>
循环方式

$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()
用于自定义模板,而
循环
用于遵循Wordpress命名约定的模板内部


我更喜欢
get_posts()
,但是如果与循环相比有很大的开销,我应该重新考虑一下。

我终于找到了答案

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

因此,如果我使用
$posts=get_posts($args),这意味着我做了不必要的额外查询


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

我终于找到了答案

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

因此,如果我使用
$posts=get_posts($args),这意味着我做了不必要的额外查询

$posts=get_posts($args)只能在模板外部使用,例如在每页上始终存在的侧栏上