自托管的 oEmbed 提供程序:一个简单的 Hello World 演示
这是一个非常简单的 自托管 oembed 提供程序(站点 A)演示,它在 oembed.com 上为 rich 实现 json 规范类型响应。其他可用的类型是 link、photo 和 video。
站点 A:
本网站是一个自托管的oembed 提供者,它支持json 格式并且只实现必需的 oembed 规范并跳过可选参数。
我们还为未找到的网址实施404,为不可用的格式实施501。
这里用到的关键函数是url_to_postid()、status_header()、get_post()和wp_send_json()。
/**
* Demo: A simple self-hosted oEmbed provider.
*/
add_action( 'template_redirect', 'simple_oembed_provider_so27693829' )
function simple_oembed_provider_so27693829()
{
// Catch the user input:
$input = filter_input_array( INPUT_GET, array(
'simple-oembed' => FILTER_SANITIZE_NUMBER_INT,
'url' => FILTER_SANITIZE_URL,
'format' => FILTER_SANITIZE_STRING,
'maxwidth' => FILTER_SANITIZE_NUMBER_INT,
'maxheight' => FILTER_SANITIZE_NUMBER_INT,
)
);
// Our oembed service is activated:
if( 1 == $input['simple-oembed'] )
{
//--------------
// We only support json format:
//--------------
if( 'json' != $input['format'] )
{
status_header( 501 );
nocache_headers();
exit();
$pid = url_to_postid( $input['url'] );
//--------------
// The url doesn't exists:
//--------------
if( 0 == $pid )
{
status_header( 404 );
nocache_headers();
exit();
}
//--------------
// json output:
//--------------
else
{
$post = get_post( $pid );
$data = array(
'version' => '1.0',
'type' => 'rich',
'width' => empty( $input['maxwidth'] ) ? 600 : min( 600, $input['maxwidth'] ),
'height' => empty( $input['maxheight'] ) ? 400 : min( 400, $input['maxheight'] ),
'html' => sprintf(
'<div class="simple-oembed"><h2><a href="%s">%s</a></h2><p>%s</p></div>',
get_permalink( $pid ),
apply_filters( 'the_title', $post->post_title ),
'Check out this great post!'
)
);
wp_send_json( $data );
}
}
}
网站 B:
要测试站点 A 提供的 oembed 服务,我们必须通过以下方式注册它:
add_action( 'init', 'add_our_oembed_provider_so27693829' );
function add_our_oembed_provider_so27693829()
{
wp_oembed_add_provider(
$format = 'http://site-a.tld/*',
$provider = 'http://site-a.tld/?simple-oembed=1&'
);
}
在站点 B。
然后当我们在编辑器中添加site-a.tld 链接时,我们得到:
保存前:
保存后:
这里site-b.tld会向site-a.tld发送如下GET请求:
http://site-a.tld/?simple-oembed=1
&format=json
&maxwidth=625
&maxheight=938
&url=http://site-a.tld/hello-world/
给出以下 200 状态响应:
{
"version":"1.0",
"type":"rich",
"width":600,
"height":400,
"html":"<div class=\"simple-oembed\"><h2><a href=\"http:\/\/site-a.tld\/hello-world\/\">Hello World from Site A<\/a><\/h2><p>Check out this great post!<\/p><\/div>"
}
ps:我没有提到自动 oEmbed 发现。
有用的资源: