[英]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.