WordPressでiframeだけoEmbedが効かない問題
いまどきのWordPressは、YouTubeやGoogle mapのURLをコンテンツエリアに貼るだけで
自動的にiframe埋め込みをしてくれるのですが、
この機能は oEmbed というヤツが担っています。
iframeだけ効かなくなった
あちこちテーマをいじっていたら、ある日突然、
自動埋め込みが効かなくなった。
直接iframeタグをコピペで貼れば埋め込まれるものの、
URL → iframeの自動変換が作動しない。
iframe以外の、たとえば他所のブログ記事URLをカード表示にする機能は、通常通り動いていた。
(その場合、iframeではなくblockquoteでカード表示される)
原因を探る
必要なファイルが読み込まれているか
参考
<link rel='https://api.w.org/' href='http://自分のドメイン/wp-json/' /> <link rel="alternate" type="application/json+oembed" href="http://自分のドメイン/wp-includes/oembed/1.0/embed?url=独自のパラメータ" /> <link rel="alternate" type="text/xml+oembed" href="http://自分のドメイン/wp-includes/oembed/1.0/embed?url=独自のパラメータ" /> <script type='text/javascript' src='http://自分のドメイン/wp-includes/js/wp-embed.min.js'></script>
ちゃんと読み込まれているのを確認。
functions.php でキャッシュをクリア
神
このサイトの2つめの方法を採用。
add_filter( 'oembed_ttl', function( $ttl, $url, $attr, $post_ID )
{
// Only do this on single posts
if( is_single() )
{
// Oembeds cached before this time, will be recached:
$recache_time = '2015-09-23 23:26:00'; // <-- Set this to the current time.
// Get the time when oEmbed HTML was last cached (based on the WP_Embed class)
$key_suffix = md5( $url . serialize( $attr ) );
$cachekey_time = '_oembed_time_' . $key_suffix;
$cache_time = get_post_meta( $post_ID, $cachekey_time, true );
// Get the cached HTML
$cachekey = '_oembed_' . $key_suffix;
$cache_html = get_post_meta( $post_ID, $cachekey, true );
// Check if we need to regenerate the oEmbed HTML:
if(
$cache_time < strtotime( $recache_time ) // cache time check
&& false !== strpos( $cache_html, 'youtube' ) // contains "youtube" stuff
&& ! do_action( 'wpse_do_cleanup' ) // let's just run this once
&& 1 === $GLOBALS['wp_embed']->usecache
) {
// What we need to skip the oembed cache part
$GLOBALS['wp_embed']->usecache = 0;
$ttl = 0;
// House-cleanoing
do_action( 'wpse_do_cleanup' );
}
}
return $ttl;
}, 10, 4 );
// Set the usecache attribute back to 1.
add_filter( 'embed_oembed_discover', function( $discover )
{
if( 1 === did_action( 'wpse_do_cleanup' ) )
$GLOBALS['wp_embed']->usecache = 1;
return $discover;
} );
これをこのままfunctions.phpに貼ったら、
無事に動くようになった!やった〜〜!!