函数文档

get_post_comments_feed_link()

💡 云策文档标注

概述

get_post_comments_feed_link() 函数用于获取指定文章的评论 Feed 永久链接。它支持自定义文章 ID 和 Feed 类型,并根据网站固定链接设置生成相应 URL。

关键要点

  • 函数返回文章评论 Feed 的永久链接,成功时返回字符串,失败时返回空字符串。
  • 参数 $post_id 可选,默认为全局 $post 的 ID;$feed 可选,默认为 get_default_feed() 的值,支持如 'rss2'、'atom' 等类型。
  • 函数内部处理包括:验证文章存在性、根据固定链接设置(permalink_structure)和文章类型(如附件、页面)构建 URL。
  • 使用 apply_filters('post_comments_feed_link', $url) Hook 允许过滤返回的链接。

代码示例

// 获取当前文章的默认评论 Feed 链接
$link = get_post_comments_feed_link();

// 获取指定文章 ID 的 Atom Feed 链接
$link = get_post_comments_feed_link( 123, 'atom' );

注意事项

  • 对于附件类型文章,如果未附加到父文章,会生成特殊的 Feed URL。
  • 函数依赖多个 WordPress 核心函数,如 get_permalink()、home_url() 等,确保环境正确配置。

📄 原文内容

Retrieves the permalink for the post comments feed.

Parameters

$post_idintoptional
Post ID. Default is the ID of the global $post.
$feedstringoptional
Feed type. Possible values include 'rss2', 'atom'.
Default is the value of get_default_feed() .

Return

string The permalink for the comments feed for the given post on success, empty string on failure.

Source

function get_post_comments_feed_link( $post_id = 0, $feed = '' ) {
	$post_id = absint( $post_id );

	if ( ! $post_id ) {
		$post_id = get_the_ID();
	}

	if ( empty( $feed ) ) {
		$feed = get_default_feed();
	}

	$post = get_post( $post_id );

	// Bail out if the post does not exist.
	if ( ! $post instanceof WP_Post ) {
		return '';
	}

	$unattached = 'attachment' === $post->post_type && 0 === (int) $post->post_parent;

	if ( get_option( 'permalink_structure' ) ) {
		if ( 'page' === get_option( 'show_on_front' ) && (int) get_option( 'page_on_front' ) === $post_id ) {
			$url = _get_page_link( $post_id );
		} else {
			$url = get_permalink( $post_id );
		}

		if ( $unattached ) {
			$url = home_url( '/feed/' );
			if ( get_default_feed() !== $feed ) {
				$url .= "$feed/";
			}
			$url = add_query_arg( 'attachment_id', $post_id, $url );
		} else {
			$url = trailingslashit( $url ) . 'feed';
			if ( get_default_feed() !== $feed ) {
				$url .= "/$feed";
			}
			$url = user_trailingslashit( $url, 'single_feed' );
		}
	} else {
		if ( $unattached ) {
			$url = add_query_arg(
				array(
					'feed'          => $feed,
					'attachment_id' => $post_id,
				),
				home_url( '/' )
			);
		} elseif ( 'page' === $post->post_type ) {
			$url = add_query_arg(
				array(
					'feed'    => $feed,
					'page_id' => $post_id,
				),
				home_url( '/' )
			);
		} else {
			$url = add_query_arg(
				array(
					'feed' => $feed,
					'p'    => $post_id,
				),
				home_url( '/' )
			);
		}
	}

	/**
	 * Filters the post comments feed permalink.
	 *
	 * @since 1.5.1
	 *
	 * @param string $url Post comments feed permalink.
	 */
	return apply_filters( 'post_comments_feed_link', $url );
}

Hooks

apply_filters( ‘post_comments_feed_link’, string $url )

Filters the post comments feed permalink.

Changelog

Version Description
2.2.0 Introduced.