2011年12月9日星期五

在wordpress中为feeds输出添加相关文章功能

 
 

satan 通过 Google 阅读器发送给您的内容:

 
 

于 11-12-9 通过 averiany涂鸦馆 作者:averainy

在wordpress中,这个功能是可以用插件插件实现的,但是用插件自然会或多或少影响性能,所以不如自己添加几行代码来的省事.
将下方的代码添加到wordpress 相应的theme中德functions.php文件中,清空缓存,之后就会在feed中看到related posts了
//related post for feed
function feed_related_posts($content)
{
        global $post;
        $showposts = 5;
        if(is_feed()){
                $tags = wp_get_post_tags($post->ID);
                if($tags) {
                        $first_tag = $tags[0]->term_id;
                        $args=array(
                                'tag__in' => array($first_tag),
                                'post__not_in' => array($post->ID),
                                'showposts'=>$showposts,
                                'caller_get_posts'=>1
                        );
                        $my_query = new WP_Query($args);
                        if($my_query->have_posts()) {
                                $content .= '<h3>Related Posts</h3>';
                                $content .= '<ul>';
                                while ($my_query->have_posts()) {
                                        $my_query->the_post();
                                        $content .= '<li><a href="'. get_permalink() .'" title="Permanent Link to '. the_title_attribute('echo=0') .'">'. get_the_title() .'</a></li>';
                                }
                                $content .= '</ul>';
                        }
                }
        }
        return $content;
}
add_filter('the_content','feed_related_posts');
这段代码中用到了两个关键的部分是is_feed() function 和 the content filter.

 
 

可从此处完成的操作:

 
 

没有评论:

发表评论