函数文档

fetch_feed()

💡 云策文档标注

概述

fetch_feed() 函数用于基于 RSS 或 Atom 源 URL 构建 SimplePie 对象,支持单 URL 或 URL 数组以合并多个源。默认缓存 12 小时,可通过过滤器调整。

关键要点

  • 参数 $url 可为字符串或字符串数组,数组时使用 SimplePie 多源功能合并
  • 返回 SimplePie 对象或 WP_Error 对象,处理错误时返回 WP_Error
  • 缓存时间可通过 wp_feed_cache_transient_lifetime 过滤器修改,默认 12 小时
  • 内部注册自定义缓存、文件和清理类,确保与 WordPress 集成
  • 支持 wp_feed_options 动作钩子,在处理前修改 SimplePie 对象

代码示例

// 示例:获取并显示 RSS 源的前 5 个条目链接
$rss = fetch_feed('http://example.com/feed');
if (!is_wp_error($rss)) {
    $maxitems = $rss->get_item_quantity(5);
    $rss_items = $rss->get_items(0, $maxitems);
    foreach ($rss_items as $item) {
        echo '<a href="' . esc_url($item->get_permalink()) . '" title="' . esc_attr($item->get_date('j F Y | g:i a')) . '">' . esc_html($item->get_title()) . '</a>';
    }
}

注意事项

  • 无需手动包含 feed.php,函数随 WordPress 自动加载
  • 空 URL 或数组处理有特殊逻辑,避免 PHP 8.5 弃用问题
  • 使用 SimplePie 1.3 或更高版本时推荐缓存注册方法,否则回退到兼容方式

📄 原文内容

Builds SimplePie object based on RSS or Atom feed from URL.

Parameters

$urlstring|string[]required
URL of feed to retrieve. If an array of URLs, the feeds are merged using SimplePie’s multifeed feature.
See also http://simplepie.org/wiki/faq/typical_multifeed_gotchas

Return

SimplePieSimplePie|WP_Error SimplePie object on success or WP_Error object on failure.

More Information

fetch_feed caches results for 12 hours by default. You can modify this by modifying the time interval via the filter wp_feed_cache_transient_lifetime.

Source

function fetch_feed( $url ) {
	if ( ! class_exists( 'SimplePieSimplePie', false ) ) {
		require_once ABSPATH . WPINC . '/class-simplepie.php';
	}

	require_once ABSPATH . WPINC . '/class-wp-feed-cache-transient.php';
	require_once ABSPATH . WPINC . '/class-wp-simplepie-file.php';
	require_once ABSPATH . WPINC . '/class-wp-simplepie-sanitize-kses.php';

	$feed = new SimplePieSimplePie();

	$feed->get_registry()->register( SimplePieSanitize::class, 'WP_SimplePie_Sanitize_KSES', true );

	/*
	 * We must manually overwrite $feed->sanitize because SimplePie's constructor
	 * sets it before we have a chance to set the sanitization class.
	 */
	$feed->sanitize = new WP_SimplePie_Sanitize_KSES();

	// Register the cache handler using the recommended method for SimplePie 1.3 or later.
	if ( method_exists( 'SimplePie_Cache', 'register' ) ) {
		SimplePie_Cache::register( 'wp_transient', 'WP_Feed_Cache_Transient' );
		$feed->set_cache_location( 'wp_transient' );
	} else {
		// Back-compat for SimplePie 1.2.x.
		require_once ABSPATH . WPINC . '/class-wp-feed-cache.php';
		$feed->set_cache_class( 'WP_Feed_Cache' );
	}

	$feed->get_registry()->register( SimplePieFile::class, 'WP_SimplePie_File', true );

	/** This filter is documented in wp-includes/class-wp-feed-cache-transient.php */
	$feed->set_cache_duration( apply_filters( 'wp_feed_cache_transient_lifetime', 12 * HOUR_IN_SECONDS, $url ) );

	/**
	 * Fires just before processing the SimplePie feed object.
	 *
	 * @since 3.0.0
	 *
	 * @param SimplePieSimplePie $feed SimplePie feed object (passed by reference).
	 * @param string|string[]     $url  URL of feed or array of URLs of feeds to retrieve.
	 */
	do_action_ref_array( 'wp_feed_options', array( &$feed, $url ) );

	if ( empty( $url ) ) {
		/*
		 * @todo: Set $url to empty string once supported by SimplePie.
		 *
		 * The early return without proceeding is to work around a PHP 8.5
		 * deprecation issue resolved in https://github.com/simplepie/simplepie/pull/949
		 *
		 * To avoid the duplicate code, this block can be replaced with `$url = '';` once SimplePie
		 * is upgraded to a version that includes the fix.
		 */
		$feed->init();
		$feed->set_output_encoding( get_bloginfo( 'charset' ) );

		if ( $feed->error() ) {
			return new WP_Error( 'simplepie-error', $feed->error() );
		}

		return $feed;
	} elseif ( is_array( $url ) && count( $url ) === 1 ) {
		$url = array_shift( $url );
	} elseif ( is_array( $url ) ) {
		$feeds            = array();
		$simplepie_errors = array();
		foreach ( $url as $feed_url ) {
			$simplepie_instance = clone $feed;
			$simplepie_instance->set_feed_url( $feed_url );
			$simplepie_instance->init();
			$simplepie_instance->set_output_encoding( get_bloginfo( 'charset' ) );

			if ( $simplepie_instance->error() ) {
				$simplepie_errors[] = sprintf(
					/* translators: %1$s is the feed URL, %2$s is the error message. */
					__( 'Error fetching feed %1$s: %2$s' ),
					esc_url( $feed_url ),
					$simplepie_instance->error()
				);
				unset( $simplepie_instance );
				continue;
			}

			$feeds[] = $simplepie_instance;
			unset( $simplepie_instance );
		}

		if ( ! empty( $simplepie_errors ) ) {
			return new WP_Error( 'simplepie-error', $simplepie_errors );
		}

		$feed->init();
		$feed->data['items'] = SimplePieSimplePie::merge_items( $feeds );
		return $feed;
	}

	$feed->set_feed_url( $url );
	$feed->init();
	$feed->set_output_encoding( get_bloginfo( 'charset' ) );

	if ( $feed->error() ) {
		return new WP_Error( 'simplepie-error', $feed->error() );
	}

	return $feed;
}

Hooks

apply_filters( ‘wp_feed_cache_transient_lifetime’, int $lifetime, string $name )

Filters the transient lifetime of the feed cache.

do_action_ref_array( ‘wp_feed_options’, SimplePieSimplePie $feed, string|string[] $url )

Fires just before processing the SimplePie feed object.

Changelog

Version Description
2.8.0 Introduced.

User Contributed Notes

  1. Skip to note 2 content

    Example
    This example will retrieve and display a list of links for an existing RSS feed, limiting the selection to the five most recent items:

    <h2></h2>
    
    get_item_quantity( 5 ); 
    
    	// Build an array of all the items, starting with element 0 (first element).
    	$rss_items = $rss->get_items( 0, $maxitems );
    
    endif;
    ?>
    
    <ul>
        
            <li></li>
        
            
            
                <li>
                    <a href="<?php echo esc_url( $item->get_permalink() ); ?>"
                        title="<?php printf( __( 'Posted %s', 'wpdocs_textdomain' ), $item->get_date('j F Y | g:i a') ); ?>">
                        get_title() ); ?>
                    </a>
                </li>
            
        
    </ul>