我們的許多初級讀者很快就開始修改他們的wordpress 主題,這就是為什么我們有一個WordPress 主題備忘單來幫助他們入門。這給新用戶帶來了一些有趣的挑戰。一位這樣的讀者最近問我們如何在 WordPress 中顯示上周的帖子。他們只是想在主頁上添加一個部分,顯示上周的帖子。在本文中,我們將向您展示如何在 WordPress 中顯示上周的帖子。
在向您展示如何顯示上周的帖子之前,我們首先看一下如何使用 WP_Query 顯示本周的帖子。將以下代碼復制并粘貼到主題的functions.php文件或特定于站點的插件中。
functionwpb_this_week() { $week= date('W');$year= date('Y');$the_query= newWP_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 中一鍵使用
在上面的示例代碼中,我們首先找出當前的星期和年份。然后,我們在 WP_Query 中使用這些值來顯示本周的帖子。現在您需要做的就是在主題文件中添加要顯示帖子的位置。
這很簡單,不是嗎?現在要顯示上周的帖子,您只需將本周的值減 1 即可。但如果這是一年中的第一周,那么該周和當年的值將為 0,而不是去年的值。以下是解決該問題的方法。
functionwpb_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= newWP_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;}
由
在 WordPress 中一鍵使用
在上面的示例代碼中,我們放置了兩項檢查。當當前周的值為 1 時,第一個檢查將上周的值設置為 52(一年中的最后一周)。當上周的值為 52 時,第二個檢查將年份的值設置為去年。
要顯示上周的帖子,您所需要做的就是添加到您想要顯示它們的主題模板文件中。或者,如果您想要一個短代碼,以便可以將其添加到頁面或小部件中,則只需將此行添加到上面給出的代碼下方即可。
add_shortcode('lastweek', 'wpb_last_week_posts');
由
在 WordPress 中一鍵使用
您現在可以在帖子、頁面或小部件中使用此短代碼,如下所示:
[lastweek]
請注意,您并不總是需要 WP_Query 來創建自定義查詢。WordPress 附帶了一些功能來幫助您顯示最近的帖子、檔案、評論等。如果有更簡單的方法來使用現有功能,那么您實際上不需要編寫自己的查詢。