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)代码>只能在模板外部使用,例如在每页上始终存在的侧栏上