0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

WordPressでYouTubeのoEmbed埋め込みをカスタマイズ

Posted at

内容

WordPressで外部コンテンツ埋め込みに使われるoEmbedはパラメーターを自由に設定できません。
ここではYouTube動画をiOSでインライン再生されるようにするplaysinlineパラメーターを追加してみます。
array_merge()の第二引数を調整することで関連動画の設定なども簡単にできます。

コード

functions.php
function embed_oembed_html_custom($cache, $url) {
  if (strpos($url, 'youtube.com') !== false || strpos($url, 'youtu.be') !== false) {
    return preg_replace_callback(
      '/<iframe.*?src\s*=\s*["|\'](.*?)["|\'].*?>/i',
      function($matches) {
        $url_query = parse_url($matches[1], PHP_URL_QUERY);
        if (empty($url_query)) {
          $query = array();
        } else {
          parse_str($url_query, $query);
        }
        $new_query = array_merge($query, array('playsinline' => '1'));
        $new_src = add_query_arg($new_query, $matches[1]);
        return str_replace($matches[1], $new_src, $matches[0]);
      },
      $cache
    );
  }
  return $cache;
}
add_filter('embed_oembed_html', 'embed_oembed_html_custom', 10, 2);
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?