WordPress教程-网站纯代码实现“历史上的今天”文章调用方法教程

WordPress实现”历史上的今天”文章调用方法,wordpress网站如何让历史文章多个展现的机会,除了相关文章推荐,站长们还经常会用到“历史上的今天”功能,即在文章末端调用前几年同一天发布的文章列表。

这个功能最初是由柳城创建的 wp-today 插件实现的,这个插件已经停更多年了,其核心代码也不复杂

第一步:复制下方代码到WordPress主题的 functions.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 .= “<li><strong>$h_year:</strong>&nbsp;&nbsp;<a href='”.$h_permalink.”‘ title='”.$h_post_title.”‘ target=’_blank’>$h_post_title($h_comments)</a></li>”;
}
}
if ( $h_post ){
$result = “<hr><h3>历史上的今天:</h3><ul>”.$h_post.”</ul>”;
}
return $result;
}
function wp_today_auto($content){
if( is_single() ){
$content = $content.wp_today();
}
return $content;
}
add_filter(‘the_content’, ‘wp_today_auto’,9999);

将代码加入到当前主题的Functions.php文件中。

第二步、指定位置调出历史文章

<?php echo wp_today(); ?>

在需要调出历史今天的位置加上上面调出代码。对于CSS样式我们自行设置添加。

实现的效果如下图

WordPress教程-网站纯代码实现“历史上的今天”文章调用方法教程

“历史上的今天”模块,调取了历史上同一天的文章列表,标注了年份,文章标题、链接和评论数,你的网站建站时间越长,则越有价值。

前几天网站的 Autumn Pro 主题进行了升级,更新后函数文件 functions.php 中自加的代码都被清空了,让我对主题更新又爱又恨。发现之前苏醒的方法挺不错,他开发的主题会在 functions.php 中引用一个子函数文件,用户自己添加的代码就写在这个文件中,这样主题升级时就不会被清空了。

文/来源:www.munue.com/355.html

版权声明:本站部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如本站内容侵犯了您的权益请联系我们,邮箱:1511977125@qq.com 我们核实后会及时处理,发布内容不代表痴痴资讯网立场,本文标题:WordPress教程-网站纯代码实现“历史上的今天”文章调用方法教程本文链接:https://www.chichizixun.com/4662.html