函数文档

get_post_embed_url()

💡 云策文档标注

概述

get_post_embed_url() 函数用于获取特定文章在 iframe 中嵌入的 URL。它根据文章 ID 或对象生成嵌入 URL,并处理路径冲突和固定链接设置。

关键要点

  • 参数 $post 可选,可以是整数(文章 ID)或 WP_Post 对象,默认为 null(当前文章)
  • 返回字符串(成功时)或 false(文章不存在时)
  • 函数内部使用 get_post() 获取文章对象,并检查其是否存在
  • 生成嵌入 URL 的基本路径为文章固定链接后添加 'embed' 路径
  • 如果未启用固定链接结构或存在路径冲突,则通过 add_query_arg() 添加查询参数 'embed=true'
  • 通过 apply_filters('post_embed_url', $embed_url, $post) 钩子允许过滤嵌入 URL
  • 最终返回经过 sanitize_url() 清理的 URL

代码示例

function get_post_embed_url( $post = null ) {
    $post = get_post( $post );

    if ( ! $post ) {
        return false;
    }

    $embed_url     = trailingslashit( get_permalink( $post ) ) . user_trailingslashit( 'embed' );
    $path_conflict = get_page_by_path( str_replace( home_url(), '', $embed_url ), OBJECT, get_post_types( array( 'public' => true ) ) );

    if ( ! get_option( 'permalink_structure' ) || $path_conflict ) {
        $embed_url = add_query_arg( array( 'embed' => 'true' ), get_permalink( $post ) );
    }

    /**
     * Filters the URL to embed a specific post.
     *
     * @since 4.4.0
     *
     * @param string  $embed_url The post embed URL.
     * @param WP_Post $post      The corresponding post object.
     */
    return sanitize_url( apply_filters( 'post_embed_url', $embed_url, $post ) );
}

注意事项

  • 函数在 WordPress 4.4.0 版本中引入
  • 相关函数包括 get_post_embed_html(),用于获取文章的嵌入 HTML 代码
  • 依赖多个辅助函数如 trailingslashit()、get_page_by_path()、add_query_arg() 等
  • 使用前应确保文章存在,否则返回 false

📄 原文内容

Retrieves the URL to embed a specific post in an iframe.

Parameters

$postint|WP_Postoptional
Post ID or object. Defaults to the current post.

Default:null

Return

string|false The post embed URL on success, false if the post doesn’t exist.

Source

function get_post_embed_url( $post = null ) {
	$post = get_post( $post );

	if ( ! $post ) {
		return false;
	}

	$embed_url     = trailingslashit( get_permalink( $post ) ) . user_trailingslashit( 'embed' );
	$path_conflict = get_page_by_path( str_replace( home_url(), '', $embed_url ), OBJECT, get_post_types( array( 'public' => true ) ) );

	if ( ! get_option( 'permalink_structure' ) || $path_conflict ) {
		$embed_url = add_query_arg( array( 'embed' => 'true' ), get_permalink( $post ) );
	}

	/**
	 * Filters the URL to embed a specific post.
	 *
	 * @since 4.4.0
	 *
	 * @param string  $embed_url The post embed URL.
	 * @param WP_Post $post      The corresponding post object.
	 */
	return sanitize_url( apply_filters( 'post_embed_url', $embed_url, $post ) );
}

Hooks

apply_filters( ‘post_embed_url’, string $embed_url, WP_Post $post )

Filters the URL to embed a specific post.

Changelog

Version Description
4.4.0 Introduced.