函数文档

do_feed()

💡 云策文档标注

概述

do_feed() 函数通过动作钩子加载 feed 模板,用于处理 WordPress 中的 feed 请求。如果 feed 没有对应的钩子,函数会终止执行并显示错误消息。

关键要点

  • 函数从查询变量中获取 feed 类型,并移除可能的前缀。
  • 如果 feed 类型为空或为 'feed',则使用默认 feed。
  • 检查是否存在对应的 do_feed_{$feed} 钩子,若无则返回 404 错误。
  • 触发 do_feed_{$feed} 动作钩子,传递是否为评论 feed 和 feed 名称参数。

代码示例

function do_feed() {
	global $wp_query;

	$feed = get_query_var( 'feed' );

	// Remove the pad, if present.
	$feed = preg_replace( '/^_+/', '', $feed );

	if ( '' === $feed || 'feed' === $feed ) {
		$feed = get_default_feed();
	}

	if ( ! has_action( "do_feed_{$feed}" ) ) {
		wp_die( __( 'Error: This is not a valid feed template.' ), '', array( 'response' => 404 ) );
	}

	do_action( "do_feed_{$feed}", $wp_query->is_comment_feed, $feed );
}

注意事项

  • 建议每个 feed 类型只设置一个钩子,以避免冲突。
  • 函数自 WordPress 2.1.0 引入,4.4.0 版本添加了 $feed 参数。
  • 可能的钩子名称包括 do_feed_atom、do_feed_rdf、do_feed_rss、do_feed_rss2。

📄 原文内容

Loads the feed template from the use of an action hook.

Description

If the feed action does not have a hook, then the function will die with a message telling the visitor that the feed is not valid.

It is better to only have one hook for each feed.

Source

function do_feed() {
	global $wp_query;

	$feed = get_query_var( 'feed' );

	// Remove the pad, if present.
	$feed = preg_replace( '/^_+/', '', $feed );

	if ( '' === $feed || 'feed' === $feed ) {
		$feed = get_default_feed();
	}

	if ( ! has_action( "do_feed_{$feed}" ) ) {
		wp_die( __( '<strong>Error:</strong> This is not a valid feed template.' ), '', array( 'response' => 404 ) );
	}

	/**
	 * Fires once the given feed is loaded.
	 *
	 * The dynamic portion of the hook name, `$feed`, refers to the feed template name.
	 *
	 * Possible hook names include:
	 *
	 *  - `do_feed_atom`
	 *  - `do_feed_rdf`
	 *  - `do_feed_rss`
	 *  - `do_feed_rss2`
	 *
	 * @since 2.1.0
	 * @since 4.4.0 The `$feed` parameter was added.
	 *
	 * @param bool   $is_comment_feed Whether the feed is a comment feed.
	 * @param string $feed            The feed name.
	 */
	do_action( "do_feed_{$feed}", $wp_query->is_comment_feed, $feed );
}

Hooks

do_action( “do_feed_{$feed}”, bool $is_comment_feed, string $feed )

Fires once the given feed is loaded.

Changelog

Version Description
2.1.0 Introduced.