繁体   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