對於使用 WordPress 來做一些諮詢站的朋友,喜歡在側邊欄顯示周文章。要達到這個目的,我們有兩個方法一是使用插件實現,另一個方法就是使用自定義代碼。本文介紹的方法使用的是代碼的方法。
一、我們來看看顯示本週的文章的代碼:
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;
}
這段代碼首先定義一下年和周的變量,然後再做一個查詢即可。代碼很簡單。
而現在我們需要的是定義上一週的文章,如何實現呢?
二、 WordPress 顯示上一週的文章
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;
這個例子代碼,我們放了兩個檢查,第一個設置如果本週為本年的第一週,則設置上一週的值為 52(上一年的最後一週),第二個檢查是如果上一週值為 52,設置年為上一年。
三、如何使用上面的代碼
1 、採用函數調用的方法
把下面的函數放在需要顯示的位置:
<?php dj_last_week_posts(); ?>
1
2 、使用簡碼的方法
在上面的代碼下面加一行:
1
add_shortcode('lastweek','dj_last_week_posts')
如何使用簡碼:
[lastweek]
插入到文章或頁面或小工具裏。