RSS提要的多个版本?一个有完整的内容,一个有摘录

时间:2012-05-27 作者:Travis Pflanz

我不知道该如何表达我的问题,我已经搜索了一整天,但没有结果。

我正在寻找一种方法来创建两个版本的RSS提要,一个包含完整内容,另一个只包含摘录。

主要是,我想为“作者”feed做这件事。我想为每个作者创建两个提要。一个有完整的内容,一个有摘录。如果没有其他内容,我希望作者RSS提要只包含摘录,但主网站RSS提要必须始终是完整内容提要。

原因是什么?该网站是一个体育网站。我想为那些想要RSS的人提供完整内容的RSS,但我也会自动在我的个人网站上发布我自己的文章(其他一些人也会这样做)。当这篇文章被发布到我自己的网站上时,我只想包括摘录,以及指向完整的原始文章的链接。

我不在乎使用的方法,无论是代码还是插件。

UPDATE

我一直在努力让迈克尔·埃克隆德(MichaelEcklund)和伊恩·邓恩(IanDunn)所描述的方法发挥作用。我两个人都没能去工作。这两种方法仍然在RSS提要中显示完整的文章,而不是摘录。

我不确定这是否有什么不同,但我只记得我使用了Advanced Excerpt 插件来管理我的网站上的摘录。我没有尝试禁用这个插件,因为它控制主页、分类页面、标签页面、作者页面等等。

4 个回复
最合适的回答,由SO网友:Ian Dunn 整理而成

我的做法是:

在“阅读选项”页面上,设置For each article in a feed, show... 选项到Full Text 因此,默认情况下,提要将包括整个帖子http://example.com/author/username/feed?format=excerpt. 确保您不使用reserved term 用于参数名称http://example.com/author/username/feed.这里有一些这样做的代码,使用format 作为参数名称。只要更新引用它的代码的每个部分,就可以使用任何想要的参数名称。将代码放入functionality plugin.

function truncateFeedContent( $content )
{
    if( get_query_var( \'format\' ) == \'excerpt\' )
    {
        $content = get_the_excerpt();
        $content = apply_filters( \'the_excerpt_rss\', $content );
    }

    return $content;
}
add_filter( \'the_content_feed\', \'truncateFeedContent\' );

function addFormatQueryVar( $queryVars )
{
    $queryVars[] = \'format\';

    return $queryVars;
}
add_filter( \'query_vars\', \'addFormatQueryVar\' );
为了避免与高级摘录插件发生冲突,请将此代码也添加到功能插件中。它将在提要URL上禁用高级摘录功能,但在所有其他页面上保持不变。

function stopAdvancedExcerptOnFeeds()
{
    if( is_feed() )
        remove_filter( \'get_the_excerpt\', array( \'AdvancedExcerpt\', \'filter\' ) );
}
add_action( \'pre_get_posts\', \'stopAdvancedExcerptOnFeeds\' );

SO网友:birgire

插件

这里有一个小插件,允许您通过一个简单的GET参数覆盖全文/摘要提要选项:

<?php
/**
 * Plugin Name: Feeds with Summary Or Full Text
 * Description: GET parameter _summary with values yes or no
 * Plugin URI:  http://wordpress.stackexchange.com/a/195197/26350
 */
add_action( \'rss_tag_pre\', function( $tag )
{
    $summary = filter_input( INPUT_GET, \'_summary\', FILTER_SANITIZE_STRING );
    if( \'yes\' === $summary )
        add_filter( \'option_rss_use_excerpt\', \'__return_true\' );
    elseif( \'no\' === $summary )
        add_filter( \'option_rss_use_excerpt\', \'__return_false\' );
} );
它尊重当前设置,不带GET参数。我使用下划线来避免可能的名称冲突,但在其他方面,我面临的挑战是保持插件非常简单;-)我们可以很容易地使用$tag 参数,将其约束为rss2或原子(如果需要)。在浏览器中测试时,请记住使用缓存破坏参数。

使用示例

example.tld/feed/?_summary=yes  // Summary
example.tld/feed/?_summary=no   // Full Text
example.tld/feed/               // Uses Default settings

example.tld/author/anna/feed/?_summary=yes  // Summary
example.tld/author/anna/feed/?_summary=no   // Full Text
example.tld/author/anna/feed/               // Uses Default settings

SO网友:Michael Ecklund

实际上,有一种非常简单的方法来完成这项特定的任务。

方法一

Follow these steps to easily create a custom RSS feed in your WordPress website:

<创建自定义页面模板。将其命名为your\\u custom\\u提要。php将第一个代码块中的代码粘贴到您的自定义提要中。php上传您的\\u自定义\\u提要。php到当前活动的WordPresstheme目录You can now access your Custom Feed at: 您的域。com/自定义源/用户段塞/

学分转到Joost de Valk 发布优秀的article. 然而,我从原始文章中稍微修改了他的代码。

<?php
/*
Template Name: Custom Feed
*/

//----------------------------------------
//  CONFIGURE THIS
//----------------------------------------
$contentType = \'excerpt\';// Enter \'excerpt\' or \'content\'
$numposts = 5;// Enter number of posts to display for each author


//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//  NO MORE CONFIGURATION NECESSARY
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

function custom_rss_date( $timestamp = null ) {
    $timestamp = ($timestamp==null) ? time() : $timestamp;
    echo date(DATE_RSS, $timestamp);
}

function custom_rss_text_limit($string, $length, $replacer = \'...\') { 
    $string = strip_tags($string);
    if(strlen($string) > $length)
    return (preg_match(\'/^(.*)\\W.*$/\', substr($string, 0, $length+1), $matches) ? $matches[1] : substr($string, 0, $length)) . $replacer;   
    return $string; 
}

function custom_rss_post_id() {
    global $wp_query;
    $thePostID = $wp_query->post->ID;
    return $thePostID;
}

$thePage = get_page(custom_rss_post_id());

$posts = query_posts(\'showposts=\'.$numposts.\'&author_name=\'.$thePage->post_name);

$lastpost = $numposts - 1;

header(\'Content-Type: \' . feed_content_type(\'rss-http\') . \'; charset=\' . get_option(\'blog_charset\'), true);
echo \'<?xml version="1.0" encoding="\'.get_option(\'blog_charset\').\'"?\'.\'>\';
?>
<rss version="2.0"
    xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:wfw="http://wellformedweb.org/CommentAPI/"
    xmlns:dc="http://purl.org/dc/elements/1.1/"
    xmlns:atom="http://www.w3.org/2005/Atom"
    xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
    xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
    <?php do_action(\'rss2_ns\'); ?>
>
    <channel>
        <title>
        <?php bloginfo_rss(\'name\'); wp_title_rss(); ?>
        </title>
        <atom:link href="<?php self_link(); ?>" rel="self" type="application/rss+xml" />
        <link>
        <?php bloginfo_rss(\'url\') ?>
        </link>
        <description>
            <?php bloginfo_rss("description") ?>
        </description>
        <lastBuildDate><?php echo mysql2date(\'D, d M Y H:i:s +0000\', get_lastpostmodified(\'GMT\'), false); ?></lastBuildDate>
        <language>
            <?php bloginfo_rss( \'language\' ); ?>
        </language>
        <sy:updatePeriod><?php echo apply_filters( \'rss_update_period\', \'hourly\' ); ?></sy:updatePeriod>
        <sy:updateFrequency><?php echo apply_filters( \'rss_update_frequency\', \'1\' ); ?></sy:updateFrequency>
        <?php foreach ($posts as $post) { ?>
        <item>
        <title><?php echo get_the_title($post->ID); ?></title>
        <link>
        <?php echo get_permalink($post->ID); ?>
        </link>
        <description>
       <?php 
            if(!empty($contentType) && $contentType == \'excerpt\'){
                echo \'<![CDATA[\'.custom_rss_text_limit($post->post_content, 500).\']]>\';
            } elseif(!empty($contentType) && $contentType == \'content\'){
                echo \'<![CDATA[\'.apply_filters(\'the_content\', $post->post_content).\']]>\';
            }         
       ?>
       </description>
        <pubDate>
            <?php custom_rss_date( strtotime($post->post_date_gmt) ); ?>
        </pubDate>
        <guid><?php echo get_permalink($post->ID); ?></guid>
        </item>
        <?php } ?>
    </channel>
</rss>

You could place this in your current active WordPress theme functions.php file:

// Tell the hourly cronjob what operation it needs to perform.
add_action(\'update_custom_user_feeds\', \'create_custom_user_feeds\');

// Create a cronjob to update our custom feeds hourly.
function cron_custom_user_feeds(){
    if(!wp_next_scheduled(\'update_custom_user_feeds\')){
        wp_schedule_event(current_time(\'timestamp\'), \'hourly\', \'update_custom_user_feeds\');
    }
}
add_action(\'init\', \'cron_custom_user_feeds\');

// Delete our hourly cronjob when the theme is changed.
function clear_custom_user_feeds(){
    wp_clear_scheduled_hook(\'update_custom_user_feeds\');
}
add_action(\'switch_theme\', \'clear_custom_user_feeds\');

// Generate the custom user feeds
function create_custom_user_feeds(){
    // "Custom Feed" is the main feed page.
    $feedParent = get_page_by_title(\'Custom Feed\', \'OBJECT\', \'page\');
    if(!$feedParent){
        $pageData = array(
            \'post_title\' => \'Custom Feed\',
            \'post_name\' => \'custom-feed\',
            \'post_status\' => \'publish\',
            \'post_type\' => \'page\'
        );
        // Create custom user feed.
        $parentID = wp_insert_post($pageData);
    } else{
        $parentID = $feedParent->ID;    
    }
    $wpUsers = get_users();
    for($i = 0; $i < count($wpUsers); $i++){
        // Check if the custom user feed already exists.
        $userFeed = get_page_by_title($wpUsers[$i]->user_nicename, \'OBJECT\', \'page\');
        if(!$userFeed){
            $pageData = array(
                \'post_title\' => $wpUsers[$i]->user_nicename,
                \'post_name\' => $wpUsers[$i]->user_nicename,
                \'post_status\' => \'publish\',
                \'post_type\' => \'page\',
                \'post_parent\' => $parentID
            );
            // Create custom user feed.
            $insertPage = wp_insert_post($pageData);
            if($insertPage){
                // Assign our custom feed template.
                update_post_meta($insertPage, \'_wp_page_template\', \'your_custom_feed.php\');
            }
        }
    }
    // Attempt to flush caches
    wp_cache_flush();
    if(function_exists(\'w3tc_objectcache_flush\')){
        w3tc_objectcache_flush();
    }
    if(function_exists(\'w3tc_pgcache_flush\')){
        w3tc_pgcache_flush();
    }
    if(function_exists(\'w3tc_minify_flush\')){
        w3tc_minify_flush();
    }
    if(function_exists(\'w3tc_dbcache_flush\')){
        w3tc_dbcache_flush();
    }
}
现在,我并不是说这个解决方案是可行的,但它是有效的。

或者,您可以使用我创建的这个类add_feed();

方法二

Directions for using this class method within your theme. (Note: This class could easily be integrated into a plugin.)

<在当前活动的WordPress主题中创建一个子目录。将其命名为:“inc”。(目录结构应如下所示:/wp-content/themes/your\\u-theme/inc/)/li>
  • 创建一个PHP文件,并将代码块放在文件的下面(此答案中的第三个/最后一个代码块)。将其另存为自定义提要。php上传自定义提要。php进入“inc”目录
  • 可能需要停用并重新激活主题才能生效
  • You can now access your Custom Feed at: 您的域。com/提要/自定义用户slug/

    Note: 您可以将前缀“custom”(自定义)更改为您想要的任何内容。只需在类构造函数中配置设置。

    <?php
    if(!class_exists(\'custom_feeds\')){
        class custom_feeds{
    
            private $feed_settings;
            private $feed_data;
    
            public function __construct(){
    
                // Configure the Feed
                $this->feed_settings[\'number_posts\'] = -1;// # of feed items, -1 means all posts
                $this->feed_settings[\'content_type\'] = \'excerpt\';// Excerpt or Content
                $this->feed_settings[\'excerpt_length\'] = 500;// if excerpt, display how many characters?
                $this->feed_settings[\'offset_posts\'] = 0;// Skip # of recent posts
                $this->feed_settings[\'custom_prefix\'] = \'custom\';// domain.com/feed/{prefix}-feed-name/
                $this->feed_settings[\'signature_link\'] = false;// add link back to your site after the content.
    
                // Specify what type of feed you want to create.
                $this->prepare_feed(\'user\');// All users, nice names
                //$this->prepare_feed(\'user\', \'some-user\');// Specific user\'s nice name
    
                // Prepare the feed
                add_action(\'init\', array($this, \'setup_custom_feeds\')); 
            }
    
            public function setup_custom_feeds(){
                global $wp_rewrite;
                // Add a feed for each type.
                foreach($this->feed_data as $type => $posts){
                    add_feed($this->feed_settings[\'custom_prefix\'].\'-\'.$type, call_user_func_array(array($this, \'display_feed\'), array($type, $posts)));
                }   
                // Flush rewrite rules.
                $wp_rewrite->flush_rules();
                // Attempt to flush caches.
                $this->flush_all_caches();          
            }
    
            public function prepare_feed($type, $nice_name=NULL){ 
                if($type == \'user\'){
                    if(!is_null($nice_name)){
                        // Get specified user.
                        $data[] = get_user_by(\'slug\', $nice_name);
                    } else{
                        // Get all users.
                        $data = get_users();
                    }
                    // Find posts for our request.
                    for($i = 0; $i < count($data); $i++){
                        $userPosts = new WP_Query(array(\'posts_per_page\' => intval($this->feed_settings[\'number_posts\']), \'author_name\' => $data[$i]->user_nicename, \'offset\' => intval($this->feed_settings[\'offset_posts\'])));
                        wp_reset_postdata();
                        if(!empty($userPosts->posts)){
                            $theData[$data[$i]->user_nicename] = $userPosts->posts;
                        }
                    }
                } 
                $this->feed_data = $theData;
            }
    
            public function display_feed($type, $posts){
                $current_feed = explode(\'/feed/\', $this->self_link());
                if($this->feed_settings[\'custom_prefix\'].\'-\'.$type == $current_feed[1]){
                    header(\'Content-Type: \'.feed_content_type(\'rss-http\').\'; charset=\'.get_option(\'blog_charset\'), true);
                    echo \'<?xml version="1.0" encoding="\'.get_option(\'blog_charset\').\'"?\'.\'>\'.PHP_EOL;
                    echo \'<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/"\';
                    do_action(\'rss2_ns\');
                    echo \'>\'.PHP_EOL;
                    echo \'<channel>\'.PHP_EOL;
                    echo \'<title>\';
                    bloginfo_rss(\'name\'); 
                    wp_title_rss();
                    echo \'</title>\'.PHP_EOL;
                    echo \'<atom:link href="\'.$this->self_link().\'" rel="self" type="application/rss+xml" />\'.PHP_EOL;
                    echo \'<link>\'.get_bloginfo_rss(\'url\').\'</link>\'.PHP_EOL;
                    echo \'<description>\'.get_bloginfo_rss(\'description\').\'</description>\'.PHP_EOL;
                    echo \'<lastBuildDate>\'.mysql2date(\'D, d M Y H:i:s +0000\', get_lastpostmodified(\'GMT\'), false).\'</lastBuildDate>\'.PHP_EOL;
                    echo \'<language>\'.get_bloginfo_rss(\'language\').\'</language>\'.PHP_EOL;
                    echo \'<sy:updatePeriod>\'.apply_filters(\'rss_update_period\', \'hourly\').\'</sy:updatePeriod>\'.PHP_EOL;
                    echo \'<sy:updateFrequency>\'.apply_filters(\'rss_update_frequency\', \'1\').\'></sy:updateFrequency>\'.PHP_EOL;
                    // Begin displaying posts in our feed.
                    foreach($posts as $post){
                        echo \'<item>\'.PHP_EOL;
                        echo \'<title>\'.$post->post_title.\'</title>\'.PHP_EOL;
                        echo \'<link>\'.get_permalink($post->ID).\'</link>\'.PHP_EOL;
                        echo \'<description>\'.PHP_EOL;
                        if($this->feed_settings[\'signature_link\']){
                            $feed_signature = \'<h3>Original Post:<br /> <a title="\'.$post->post_title.\'" href="\'.get_permalink($post->ID).\'">\'.$post->post_title.\'</a></h3>\';
                        } else{
                            $feed_signature = \'\';
                        }
                        if(!empty($this->feed_settings[\'content_type\']) && $this->feed_settings[\'content_type\'] == \'excerpt\'){
                            echo \'<![CDATA[\'.$this->custom_rss_text_limit($post->post_content, intval($this->feed_settings[\'excerpt_length\'])).$feed_signature.\']]>\'.PHP_EOL;
    
                        } elseif(!empty($this->feed_settings[\'content_type\']) && $this->feed_settings[\'content_type\'] == \'content\'){
                            echo \'<![CDATA[\'.apply_filters(\'the_content\', $post->post_content).$feed_signature.\']]>\'.PHP_EOL;
                        }         
                        echo \'</description>\'.PHP_EOL;
                        echo \'<pubDate>\'.$this->custom_rss_date(strtotime($post->post_date_gmt)).\'</pubDate>\'.PHP_EOL;
                        echo \'<guid>\'.$post->guid.\'</guid>\'.PHP_EOL;
                        echo \'</item>\'.PHP_EOL;
                    }
                    echo \'</channel>\'.PHP_EOL;
                    echo \'</rss>\'.PHP_EOL;
                }
            }
    
            private function custom_rss_date($timestamp = null){
                $timestamp = ($timestamp==null) ? time() : $timestamp;
                return date(DATE_RSS, $timestamp);
            }
    
            private function custom_rss_text_limit($string, $length, $replacer = \'...\'){ 
                $string = strip_tags($string);
                if(strlen($string) > $length)
                    return (preg_match(\'/^(.*)\\W.*$/\', substr($string, 0, $length+1), $matches) ? $matches[1] : substr($string, 0, $length)) . $replacer;   
                return $string; 
            }
    
            private function self_link(){
                $host = @parse_url(home_url());
                $host = $host[\'host\'];
                $return = esc_url(
                    \'http\'
                    . ( (isset($_SERVER[\'https\']) && $_SERVER[\'https\'] == \'on\') ? \'s\' : \'\' ) . \'://\'
                    . $host
                    . stripslashes($_SERVER[\'REQUEST_URI\'])
                );
                return $return;
            }
    
            private function flush_all_caches(){
                wp_cache_flush();
                if(function_exists(\'w3tc_objectcache_flush\')){
                   w3tc_objectcache_flush();
                }
                if(function_exists(\'w3tc_pgcache_flush\')){
                   w3tc_pgcache_flush();
                }
                if(function_exists(\'w3tc_minify_flush\')){
                   w3tc_minify_flush();
                }
                if(function_exists(\'w3tc_dbcache_flush\')){
                   w3tc_dbcache_flush();
                }
            }
    
        }// END custom_feeds class.
    
        // Instantiate the class.
        $custom_feeds = new custom_feeds();
    
    }// END custom_feeds class exists.
    ?>
    
    Note: 我不知道它在大型网站上的表现如何。尽管如此,我设置这个类的方式允许轻松操作。您可以使用这个类来生成自定义帖子类型的提要,也可以使用自定义分类法。我的自定义Feeds类已经在WordPress 3.4.1上进行了测试,并且工作正常。

    如果您想以我当前设置的方式使用它,那么只需在类构造函数中配置提要设置。

    <小时>

    SO网友:Dan Cortazio

    YoU WoULD A.CCEss A. sHoRT 五、ERs我oN W我TH E十、CERPT oN THE A.DDREss:&#十、A.;HTTP://WWW.D我CA.Z我NE.CoM.BR/A.UTHoR/A.DM我N/FEED?五、ERs我oN=sHoRT

    &#十、A.;&#十、A.;

    THE LEss THE BETTER:

    &#十、A.;&#十、A.;

    A.DD_F我LTER(\'THE_CoNTENT\',\'A.UTHoR_FEED_五、ERs我oN\',1.0);&#十、A.;FUNCT我oN A.UTHoR_FEED_五、ERs我oN($CoNTENT) {&#十、A.;    我F(我s_FEED()){&#十、A.;        我F($_GET[\'五、ERs我oN\'] == \'五、ERs我oN\')&#十、A.;            $CoNTENT = L我M我T_WoRDs(sTR我P_TA.Gs($CoNTENT),1.00);&#十、A.;    }&#十、A.;    RETURN $CoNTENT;
    &#十、A.;}&#十、A.;FUNCT我oN L我M我T_WoRDs($sTR我NG, $WoRD_L我M我T){&#十、A.; $WoRDs = E十、PLoDE(“” “”,$sTR我NG);&#十、A.; RETURN 我MPLoDE(“” “”,A.RRA.Y_sPL我CE($WoRDs,0,$WoRD_L我M我T));&#十、A.;}

    &#十、A.;

    结束

    相关推荐

    如何使<!--More-->在RSS提要中具有像在帖子中一样的功能

    我正在处理一个让我发疯的RSS提要问题。我已经开始在我最近的博客中手动添加帖子,以便在所需的位置截断帖子,并诱使人们点击帖子页面以完成阅读。换句话说,我通过插入来手动指定摘要的长度。我的网站正是按照我希望的方式工作的,但我希望我的RSS提要也能以同样的方式工作。换句话说,我希望我的RSS提要中的帖子在原始帖子处被切断并链接到原始帖子,这样订阅者就必须访问我的网站才能继续阅读。我知道这是可能的,因为我最喜欢的一些博客就是这样工作的(例如101cookbooks.com和smittenkitchen.com)