[英]Wordpress change the order of posts through the standard loop
是否可以在保持标准 Wordpress 循环不变的情况下订购帖子(即无需创建全新的 WP_Query?
通过标准循环,我的意思是:
<?php if ( have_posts() ) : ?>
<?php /* The loop */ ?>
<?php while ( have_posts() ) : the_post(); ?>
我可以在此代码中指定顺序吗?
作为记录在query_posts
功能页面:
强烈建议您改用
pre_get_posts
过滤器,并通过检查is_main_query
更改主查询。
您可以在主题functions.php
文件中的pre_get_posts
上添加一个新操作,例如:
function homepage_posts($query)
{
if ($query->is_home() && $query->is_main_query())
{
$query->set( 'orderby', 'title' );
}
}
add_action('pre_get_posts', 'homepage_posts');
wp_reset_query()是要走的路
示例片段
<?php query_posts(array('orderby'=>'title','order'=>'DESC'));
if ( have_posts() ) :
while ( have_posts() ) : the_post(); ?>
<a href="<?php the_permalink() ?>"><?php the_title() ?></a><br /><?php
endwhile;
endif;
wp_reset_query();
但请记住:query_posts() 会更改您的主要查询,不推荐使用。 仅在绝对必要时使用(请参阅 query_posts:警告)。 二级循环首选创建 WP_Query 或 get_posts() 的新实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.