ワードプレスのwp_oembed_get関数の使用方法・解説

概要

wp_oembed_get 関数は、oEmbedに対応したページの埋め込み用コンテンツを取得するための関数です。この関数は、特定のURLに関連するコンテンツを埋め込む際によく使用されます。主に以下のような機能を実装する際に利用されます。

  1. YouTube動画の埋め込み
  2. Vimeo動画の埋め込み
  3. Twitterタイムラインの埋め込み
  4. Instagramの投稿の埋め込み
  5. SoundCloudトラックの埋め込み
  6. Spotifyプレイリストの埋め込み
  7. Facebook投稿の埋め込み
  8. Google Mapsの地図表示

構文

wp_oembed_get( $url, $args );

パラメータ

  • $url (string) – 埋め込みたいコンテンツのURL。
  • $args (array) – 埋め込みに関する任意の追加オプション。

戻り値

  • string|false – 埋め込み用HTMLコードが成功した場合は文字列、それ以外は false を返します。

関連する関数

使用可能なバージョン

  • WordPress 2.9以降で使用可能。

コアファイルのパス

  • wp-includes/media.php

この関数のアクションでの使用可能性

アクション名 使用可能性
mu_plugin_loaded
registered_post_type
plugins_loaded
wp_roles_init
setup_theme
after_setup_theme
set_current_user
init
register_sidebar
wp_loaded
send_headers
parse_query
pre_get_posts
wp
template_redirect
get_header
wp_head

サンプルコード

サンプルコード1:YouTube動画の埋め込み

このコードは、YouTube動画のURLを指定し、その埋め込み用HTMLを取得します。

$url = 'https://www.youtube.com/watch?v=dQw4w9WgXcQ';
$embed_code = wp_oembed_get( $url );
echo $embed_code;

引用元: https://developer.wordpress.org/reference/functions/wp_oembed_get/

サンプルコード2:Instagramの投稿の埋め込み

指定したInstagramの投稿URLから埋め込みHTMLコードを取得します。

$url = 'https://www.instagram.com/p/CIYz_C4nmN4/';
$embed_code = wp_oembed_get( $url );
echo $embed_code;

引用元: https://developer.wordpress.org/reference/functions/wp_oembed_get/

サンプルコード3:Twitterツイートの埋め込み

このサンプルは、指定のツイートのURLから埋め込むコードを取得します。

$url = 'https://twitter.com/twitter/status/1234567890123456789';
$embed_code = wp_oembed_get( $url );
echo $embed_code;

引用元: https://developer.wordpress.org/reference/functions/wp_oembed_get/

サンプルコード4:SoundCloudトラックの埋め込み

SoundCloudのトラックを埋め込むためのHTMLを取得します。

$url = 'https://soundcloud.com/user/tracks';
$embed_code = wp_oembed_get( $url );
echo $embed_code;

引用元: https://developer.wordpress.org/reference/functions/wp_oembed_get/

サンプルコード5:Facebook投稿の埋め込み

Facebookの投稿のURLから埋め込みHTMLを取得するコードです。

$url = 'https://www.facebook.com/facebook/posts/10153231379546729';
$embed_code = wp_oembed_get( $url );
echo $embed_code;

引用元: https://developer.wordpress.org/reference/functions/wp_oembed_get/

この関数について質問する


上の計算式の答えを入力してください