前几天在柳城博主的wordpress插件:历史上的今天wp-today,有很多网友说这个插件很实用,希望折腾成纯代码版分享。其实这个都是wordpress插件多了会拖慢网页打开速度的心理在作怪,不过本站也想添加这个功能,所以就顺手折腾成纯代码版分享给大家。

纯代码实现历史上的今天这个功能,还是非常简单的,只需要把wp-today插件的部分代码拿出来修改一下就可以了。我们只需要将以下代码添加到我们主题的function.php文件中即可实现在文章最后添加历史上的今天这个功能。
//历史上的今天,代码来自柳城博主的wp-today插件
function wp_today(){
global $wpdb;
$post_year = get_the_time('y');
$post_month = get_the_time('m');
$post_day = get_the_time('j');
$sql = "select id, year(post_date_gmt) as h_year, post_title, comment_count from
$wpdb->posts where post_password = '' and post_type = 'post' and post_status = 'publish'
and year(post_date_gmt)!='$post_year' and month(post_date_gmt)='$post_month' and day(post_date_gmt)='$post_day'
order by post_date_gmt desc limit 5";
$histtory_post = $wpdb->get_results($sql);
if( $histtory_post ){
foreach( $histtory_post as $post ){
$h_year = $post->h_year;
$h_post_title = $post->post_title;
$h_permalink = get_permalink( $post->id );
$h_comments = $post->comment_count;
$h_post .= "
- $h_year:
“; } } if ( $h_post ){ $result = ”
历史上的今天:
- “.$h_post.”
“; } return $result; } function wp_today_auto($content){ if( is_single() ){ $content = $content.wp_today(); } return $content; } add_filter(‘the_content’, ‘wp_today_auto’,9999);
温馨提示:
1、以上代码默认是将历史上的今天添加到文章的最后,如果需要人工设置位置,只需要将29-35行的代码删除,然后在指定位置添加以下代码即可:
2、具体的css样式大家自行调整即可。
3、效果请看下面↓

![软件推荐[wordpress]wp缓存加速插件wp rocket 3.10.1免授权版-哎呦不错往前方资源网](https://img.qianfangzy.com/i/2023/02/03/132446-0.webp)





