簡體   English   中英

顯示按日期排序的所有帖子

[英]Display all posts ordered by date

默認情況下,WordPress主頁顯示最新帖子。 如何在不是主頁的頁面上顯示最新帖子?

我的第一個目標“目標A”是讓首頁顯示一個稱為“熱門帖子”的類別(而不是最新帖子)。 “目標B”將在菜單上鏈接到按日期排序的所有帖子,也就是“最新帖子”。

我已經用下面的代碼完成了目標A。 如何完成“目標B”? 我可以創建一個名為“ New”的類別,並在菜單上創建一個鏈接,但是如何使它顯示按日期排序的所有帖子? 還是有更好的方法?


“目標A”代碼:在首頁上顯示特定類別

function popular_category( $query ) {
    if ( $query->is_home() && $query->is_main_query() ) {
    $query->set( 'category_name', 'popular' );
    }
}
add_action( 'pre_get_posts', 'popular_category' );

我認為最好的辦法是使用博客頁面創建靜態首頁。 這似乎適合您想要做的事情

方法如下:

第1步

您應該刪除問題中的代碼。 在這里沒有必要

第2步

復制page.php (或index.php )並將其重命名為front-page.php 打開它,然后用自定義查詢替換循環,該查詢將僅顯示所需類別的帖子。 不幸的是, pre_get_posts在靜態首頁上不起作用,因此在這里您將不得不使用自定義查詢。

<?php
// set the "paged" parameter (use 'page' if the query is on a static front page)
$paged = ( get_query_var( 'page' ) ) ? get_query_var( 'page' ) : 1;

// the query
$the_query = new WP_Query( 'category_name=popular&posts_per_page=10&paged=' . $paged ); 
?>

<?php if ( $the_query->have_posts() ) : ?>

<?php
// the loop
while ( $the_query->have_posts() ) : $the_query->the_post(); 
?>
<?php the_title(); ?>
<?php endwhile; ?>

<?php

// next_posts_link() usage with max_num_pages
next_posts_link( 'Older Entries', $the_query->max_num_pages );
previous_posts_link( 'Newer Entries' );
?>

<?php 
// clean up after the query and pagination
wp_reset_postdata(); 
?>

<?php else:  ?>
<p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
<?php endif; ?>

請記住,要在靜態首頁上進行分頁,您必須使用page ,而不是像其他所有自定義查詢一樣使用paged

步驟3

復制index.php並將其重命名為home.php 這將是您的博客頁面模板

第四步

現在,您可以在背面設置靜態首頁和博客頁面。 您應該在這里閱讀有關設置靜態首頁和博客頁面的信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM