很多朋友都喜歡在網(wǎng)站上調(diào)用某段時(shí)間的文章,今天來(lái)分享一下 WordPress 調(diào)用本周和上周文章的方法。
獲取本周文章
我們先來(lái)認(rèn)識(shí)一下通過(guò) WP_Query 調(diào)用本周文章的方法,將下面的代碼添加到主題的 functions.php 文件:
/**
* WordPress 調(diào)用本周的文章
* http://www.ydqwiac.cn/display-last-weeks-posts-in-wordpress.html
*/
function wpdx_this_week_posts() {
$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( '抱歉,沒(méi)有找到符合條件的文章' ); ?></p>
<?php endif;
}
// 添加簡(jiǎn)碼
add_shortcode('thisweek', 'wpdx_this_week_posts');
在上面的代碼中,我們先獲取當(dāng)前年份和本周,然后使用 WP_Query 來(lái)查詢本周的文章,然后你就可以模板文件中使用一下代碼調(diào)用:
<?php wpdx_this_week_posts(); ?>
或者在文章或頁(yè)面中使用下面的簡(jiǎn)碼調(diào)用:
[thisweek]
是不是很簡(jiǎn)單?
獲取上周文章
按照這個(gè)思路,我們可以將獲取的周數(shù)減一,就可以獲取上周文章了,但如果是一年的第一周,周數(shù)就會(huì)返回 0,而且年份是今年,不是去年了。下面的代碼已經(jīng)修復(fù)了這個(gè)問(wèn)題:
/**
* WordPress 調(diào)用上周的文章
* http://www.ydqwiac.cn/display-last-weeks-posts-in-wordpress.html
*/
function wpdx_last_week_posts() {
$thisweek = date('W'); //獲取本周數(shù)
if ($thisweek != 1) { //如果本周不是第一周,減 1 就是上周
$lastweek = $thisweek - 1;
}else{ // 如果本周是第一周,上周就是去年的 52 周
$lastweek = 52;
}
$year = date('Y'); // 獲取當(dāng)前年份
if ($lastweek != 52) { // 如果本周不是一年最后一周(52周),年份就是今年
$year = date('Y');
}else{ // 如果是最后一周,年份減 1 就是去年
$year = date('Y') -1;
}
$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( '抱歉,沒(méi)有找到符合條件的文章' ); ?></p>
<?php endif;
}
// 添加簡(jiǎn)碼
add_shortcode('lastweek', 'wpdx_last_week_posts');
上面的代碼注釋中已經(jīng)有解釋,大家自己看一下就明白了。
將上面代碼添加到當(dāng)前主題的 functions.php,就可以在模板文件使用下面的代碼調(diào)用上周的文章:
<?php wpb_last_week_posts(); ?>
或者在文章或頁(yè)面使用下面的簡(jiǎn)碼:
[lastweek]
參考資料:http://www.wpbeginner.com/wp-tutorials/how-to-display-last-weeks-posts-in-wordpress/




