wordpress如何显示上一周的文章

2014/01/17

对于使用wordpress来做一些咨询站的朋友,喜欢在侧边栏显示周文章。要达到这个目的,我们有两个方法一是使用插件实现,另一个方法就是使用自定义代码。本文介绍的方法使用的是代码的方法。

一、我们来看看显示本周的文章的代码:

[php]
function dj_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;
}
[/php]

 

这段代码首先定义一下年和周的变量,然后再做一个查询即可。代码很简单。

而现在我们需要的是定义上一周的文章,如何实现呢?

二、wordpress显示上一周的文章

[php]
function dj_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;
[/php]

 

这个例子代码,我们放了两个检查,第一个设置如果本周为本年的第一周,则设置上一周的值为52(上一年的最后一周),第二个检查是如果上一周值为52,设置年为上一年。

三、如何使用上面的代码

1、采用函数调用的方法

把下面的函数放在需要显示的位置:

[php]

<?php dj_last_week_posts(); ?>

[php]

2、使用简码的方法

在上面的代码下面加一行:

[php]
add_shortcode(‘lastweek’,’dj_last_week_posts’)
[/php]

 

如何使用简码:

[lastweek]

插入到文章或页面或小工具里。

2 thoughts on “wordpress如何显示上一周的文章

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注