本功能是展示站内历史上的今天发布的文章,而不是之前历史上发生的大事。所以想正常使用本功能,首先需要的是你站点运行超过1年了,如果还不到一年,那自然不会有什么历史上的今天了。
今天我就给大家带来如何无需插件使用代码来实现历史上的今天这个功能,本功能是使用wordpress自带的date_query来实现。
实现方法
下面的代码加入到functions.php中
function fa_today_in_histroy(){ $today = getdate(); $args = array( 'date_query' => array( array( 'year' => $today['year'], 'compare' => '!=', ), array( 'month' => $today['mon'], 'day' => $today['mday'], ), ), ); $postlist = get_posts($args); $html = '历史上的今天
'; if(!empty($postlist)){ foreach ($postlist as $key => $post) { $html .= '- ID) . '" title="' . $post->post_title . '">' . $post->post_title . '
'; } $html .= '
'; return $html; }}
注意,在这个循环中是不能直接调用各种wp文章函数的,如需使用wp文章函数,则需要使用setup_postdata()
和wp_reset_postdata()
调用方法
如果是添加到文章末尾,可直接使用如下钩子,直接添加到functions.php
中即可
function add_today_in_histroy($content){ global $post; return $content . today_in_histroy();}add_filter('the_content','add_today_in_histroy');
如果是自定义位置,则使用
你可能想看:
发表评论
共有[ 1 ]人发表了评论