使用代码DIY

2024-01-19 16:26 小编

第一步:先下载我写的XML文件,里面有12个XML文件,对应12个月份,之所以12个文件也是为了日后的维护方便和读取数据的速度更加快速。如果要修改历史内容,直接编辑 xml 文件即可。

第二步:将下载好的12个XML文件放到你的网站根目录

第三步:在你当前主题的 functions.php 文件中追加如下代码:

function dateFromClmao(){ date_default_timezone_set('PRC'); $i=date('n',time()); $filename='today'.$i.'.xml'; $xml=simpleXML_load_file($filename); $todaytime="date".date("n\mj\d",time());return $xml->$todaytime->date;} function eventFromClmao(){ date_default_timezone_set('PRC'); $i=date('n',time()); $filename='today'.$i.'.xml'; $xml=simpleXML_load_file($filename); $todaytime="date".date("n\mj\d",time());return $xml->$todaytime->event;}

第四步:在你想输出”历史上的今天的地方”的模板文件地方如此,样式自己添加

<?php echo dateFromClmao(); ?> //这个是输出时间,如果当天是节日,会显示成”4月1日 愚人节”<?php echo eventFromClmao(); ?> //这个是历史事件,如显示成”1945年,美军开始大规模轰炸日本本土。”

可以看看下面的效果:

 

以上内容出自:http://www.clmao.com/?p=759

倡萌补充:看了一下上面的两个函数,大体一样,所以简单综合下,可以写成一个函数,添加一个参数判断:

/** * 为你的 WordPress 站点添加”历史上的今天”功能 * https://www.wpdaxue.com/today-in-history.html */function wpdx_today_in_history($type){ date_default_timezone_set('PRC'); $i=date('n',time()); $filename='today'.$i.'.xml'; $xml=simpleXML_load_file($filename); $todaytime="date".date("n\mj\d",time());if($type = 'date') return $xml->$todaytime->date; elseif ($type = 'event') return $xml->$todaytime->event;}

将上面的代码添加到当前主题的 functions.php 即可,调用方法如下:

<?php if(function_exists('wpdx_today_in_history')) echo wpdx_today_in_history('date'); ?> //这个是输出时间,如果当天是节日,会显示成“4月1日 愚人节”<?php if(function_exists('wpdx_today_in_history')) echo wpdx_today_in_history('event'); ?> //这个是历史事件,如显示成“1945年,美军开始大规模轰炸日本本土。”

其实还可以再综合一下,直接写成一个函数调用,同样添加到主题的 functions.php:

/** * 为你的 WordPress 站点添加”历史上的今天”功能 * https://www.wpdaxue.com/today-in-history.html */function wpdaxue_today_in_history(){ date_default_timezone_set('PRC'); $i=date('n',time()); $filename='today'.$i.'.xml'; $xml=simpleXML_load_file($filename); $todaytime="date".date("n\mj\d",time()); echo ' <div> <p>'.$xml->$todaytime->date.'</p> <p>'.$xml->$todaytime->event.'</p> </div> ';}

然后使用下面的代码,就可以直接输出日期和事件:

<?php if(function_exists('wpdaxue_today_in_history')) wpdaxue_today_in_history(); ?>


Tag: 代码
在线咨询 拨打电话

电话

13363039260

微信二维码

微信二维码