前几天在柳城博主的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: $h_post_title($h_comments)
“; } } 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、效果请看下面↓