很多网站在一级目录下放置博客并提供RSS内容订阅,如在www.example.com/根目录下放置主站,在www.example.com/blog/下放置博客,本文分享“如何将WordPress中的RSS生成html列表以供根目录下的网站调用”起到根目录内容实时更新的作用(参见:如何从论坛调出html格式的帖子)。以www.xueyueyu.com为例,其RSS地址为http://www.xueyueyu.com/feed/,现在我们要把这个RSS内容处理生成html格式的列表并每天更新至newposts.htm(博客目录下)。实现方法如下:
在博客当前主题目录下的functions.php内添加如下代码:
- add_action('my_daily_event', 'do_this_daily');
- function my_activation() {
- if ( !wp_next_scheduled( 'my_daily_event' ) ) {
- wp_schedule_event(time(), 'daily', 'my_daily_event');
- }
- }
- add_action('wp', 'my_activation');
- function do_this_daily() {
- $doc = new DOMDocument();
- $doc->load('http://www.xueyueyu.com/feed/'); /*修改为你自己的RSS地址*/
- $newhtml = '';
- foreach ($doc->getElementsByTagName('item') as $node) {
- $link = $node->getElementsByTagName('link')->item(0)->nodeValue;
- $title = $node->getElementsByTagName('title')->item(0)->nodeValue;
- $newhtml .= '<li><a target="_blank" href="'.$link.'">'.$title.'</a></li>';
- }
- /*生成最新文章列表到博客根目录的newposts.htm文件中*/
- $newfile="newposts.htm";
- $file = fopen ($newfile, "w");
- fwrite($file, $newhtml);
- fclose ($file);}
评论0