我们的许多初级读者很快就开始修改他们的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中使用这些值来显示当前周的帖子。现在您需要做的就是添加&lt;?php wpb_this_week();?&gt; 在您要显示帖子的主题文件中。

这很简单,不是吗?现在要显示上周帖子,你需要做的就是从周的值减去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.

显示上周帖子,您需要做的就是添加&lt;?php wpb_last_week_posts();?&gt; 到你想要显示它们的主题模板文件。或者,如果您想要一个短代码,以便将其添加到页面或窗口小部件中,那么只需在上面给出的代码下面添加这一行。

add_shortcode("lastweek", "wpb_last_week_posts");

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

[lastweek]

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

评论被关闭。