跳到主要内容

我们的许多初学者读者很快就会开始修改WordPress主题,这就是为什么我们拥有WordPress主题备忘单来帮助他们入门的原因。这给新用户带来了一些有趣的挑战。其中一位读者最近问我们如何在WordPress中显示上周的帖子。他们只是想在首页上添加一个部分,以显示上周的帖子。在本文中,我们将向您展示如何在WordPress中显示上周的帖子。

在向您展示如何显示上周的帖子之前,让我们首先看一下如何使用WP_Query显示本周的帖子。将以下代码复制并粘贴到主题的functions.php文件或特定于站点的插件中。

function wpb_this_week() { 
$week = date('W');
$year = date('Y');
$the_query = new WP_Query( 'year=' . $year . '&w=' . $week );
if ( $the_query->have_posts() ) : 
while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
    <h2><a href="<?php the_permalink(); ?>" title="Permanent link to <?php the_title(); ?> "><?php the_title(); ?></a></h2>
	<?php the_excerpt(); ?>
  <?php endwhile; ?>
  <?php wp_reset_postdata(); ?>
<?php else:  ?>
  <p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
<?php endif;
}

在上面的示例代码中,我们首先找出当前的星期和年份。然后,我们在WP_Query中使用这些值来显示当前星期的帖子。现在,您需要做的就是<?php wpb_this_week(); ?>在主题文件中添加要显示帖子的位置。

这很简单,不是吗?现在要显示上周的帖子,您需要做的就是从周值减去1。但是,如果这是一年中的第一周,那么该周和当前年份(而不是去年)将为0。这是解决此问题的方法。

function wpb_last_week_posts() { 
$thisweek = date('W');
if ($thisweek != 1) :
$lastweek = $thisweek - 1;   
else : 
$lastweek = 52;
endif; 
$year = date('Y');
if ($lastweek != 52) :
$year = date('Y');
else: 
$year = date('Y') -1; 
endif;
$the_query = new WP_Query( 'year=' . $year . '&w=' . $lastweek );
if ( $the_query->have_posts() ) : 
while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
    <h2><a href="<?php the_permalink(); ?>" title="Permanent link to <?php the_title(); ?> "><?php the_title(); ?></a></h2>
	<?php the_excerpt(); ?>
  <?php endwhile; ?>
  <?php wp_reset_postdata(); ?>
<?php else:  ?>
  <p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
<?php endif;

}

在上面的示例代码中,我们进行了两次检查。当当前星期的值为1时,第一张检查将最后一周的值设置为52(这是一年中的最后一周),第二张检查将上周的值设为52,则将年份的值设置为去年。

要显示上周的帖子,您只需将其添加<?php wpb_last_week_posts(); ?>到主题的模板文件中即可在其中显示它们。或者,如果您想输入一个简码,以便可以将其添加到页面或小部件中,则只需在上面给出的代码下方添加此行。

add_shortcode('lastweek', 'wpb_last_week_posts');

现在,您可以在帖子,页面或小部件中使用此短代码,如下所示:

[lastweek]

请注意,您并非始终需要WP_Query来创建自定义查询。WordPress附带了一些功能来帮助您显示最新的帖子,档案,评论等。如果有一种更简单的方法来使用现有功能,那么您实际上不需要编写自己的查询。

我们希望本文能帮助您显示WordPress上周的帖子。

回到顶部