前段时间,Smashing Magazine的文章“10 Useful RSS-Tricks and Hacks For WordPress”第三条讲怎么在RSS Feed中插入任意内容。实际上该hack出自wprecipes,但是很遗憾,它已身在高墙外了。
这种方法就是添加两个filter,分别在the_excerpt_rss和the_content_rss. 貌似合理,但实际上呢?且看wp-includes/feed-rss2.php的关键部分:
[code lang=’php’]
post_content ) > 0 ) : ?>
[/code]
首先鄙视一下RSS中只输出摘要的blogger,这样我们就只需关心外层if判断的else块了。Feed中的每个item都有一个description标签,调用的是the_excerpt_rss函数。而最重要的是content:encoded这个标签,因为多数RSS阅读器都是根据这里的内容显示的。可以看到,如果文章内容不为空——该条件99.9%的情况下成立,content:encoded的内容就是调用the_content. 该文件输出的是RSS 2.0格式,大部分WordPress blog的默认feed.
再看feed-rss.php, feed-rdf.php和feed-atom.php,只有feed-rss.php输出的RSS 0.92格式的feed没有使用the_content. 因此,按照Smashing Magazine的方法,绝大多数情况下我们添加的内容不会再RSS阅读器中显示。
所以正确的做法是把’the_content’也加上filter:
[code lang=’php’]function process_feed($content) {
if (is_feed()) { // 只在feed输出时处理,不影响站内内容显示
$content = …;
}
return $content;
}
add_filter(‘the_content’, ‘process_feed’);[/code]
最后看一下the_excerpt_rss这个函数到底都干了些什么。它定义在wp-includes/feed.php中,首先调用get_the_excerpt函数,然后应用hook到’the_excerpt_rss’的filter. get_the_excerpt定义在wp-includes/post-template.php中,取得文章的post_excerpt,然后应用hook到’get_the_excerpt’的filter,默认是wp-includes/formatting.php中的wp_trim_excerpt函数。它的作用是当post_excerpt为空的时候(该条件绝大多数情况下成立,我还没见过谁去写那个excerpt——默认在WP文章编辑器下方),取得文章内容,然后应用’the_content’的filter,再做一些去除tag的工作。总结:the_excerpt_rss就是取得the_content的输出,然后去除HTML标签。
我们hook了’the_content’,所添加的内容,自然会进入the_excerpt_rss的输出(只是html tag被抹掉了),所以不要再hook ‘the_excerpt_rss’了,以免造成内容重复!当然对于那些有精力写excerpt的牛人另当别论。
我目前的做法就是将处理函数hook到’the_content’和’the_content_rss’这两个上面。
WordPress这部分现在似乎有点乱,不知道我有没有写错什么。如有错误,请指正,呵呵。
Leave a Reply