WordPressで記事の一番最初の動画(YouTube)を取得する方法

WordPressで記事の一番最初の【画像】を取得する方法はよく見ますが、【動画】を取得する方法は見たことがなかったので。

参考
記事内の一番最初の画像を取得してサムネイル画像表示

まず、記事の一番最初の【画像】を取得する方法

functions.phpにコードを追加

function catch_that_image() {
	global $post, $posts;
	$first_img = '';
	$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
	$first_img = $matches [1] [0];
	if(empty($first_img)){ //Defines a default image
		$first_img = "dummy.jpg";
	 }
	return $first_img;
}

出力時の記述

<img src="<?php echo catch_that_image(); ?>" />

※width、heightなどのオプションは任意でどうぞ。

続いて、記事の一番最初の【動画】を取得する方法

functions.phpにコードを追加

function catch_post_movie() {
	global $post;
	$first_movie = '';
	preg_match_all('/<iframe.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
	if (isset($matches[1])) {
		$first_movie = $matches[1][0];
	}
	if(empty($first_movie)){
		$first_movie = '';
	}
	return $first_movie;
}

出力時の記述

<iframe width="640" height="360" src="<?php echo catch_post_movie(); ?>" frameborder="0" allowfullscreen=""></iframe>

※ width、heightやiframeのオプションは任意の記述に変更してください。

なにも難しいことをしてないですね。
imgをiframeに替えただけです。
そのため、動画以外にiframeを使用していたら、それも取得してきてしまいます。もしyoutubeだけに絞りたい場合は、4行目の正規表現部分【[\'”]([^\'”]+)[\'”]】を修正してください。

 

(追記 2016/9/30)

YouTubeに限った場合のやり方も掲載して欲しい、とのことで。
せっかくなので、「記事の一番最初の【画像】を取得する方法」とは違う方法でやります。

functions.phpにコードを追加

function catch_post_movie() {
	$youtubePost = esc_attr(get_the_content());
	preg_match('/www.youtube.[-_\/A-Za-z0-9]*/', $youtubePost, $matches);
	$youtubeURL = 'https://' . $matches[0] . '?rel=0';
	if(isset($matches[0])){
		echo $youtubeURL;
	}
}

$youtubeURLで追加している「’?rel=0’」などのオプションは任意でどうぞ。

出力時の記述

<iframe width="640" height="360" src="<?php echo catch_post_movie(); ?>" frameborder="0" allowfullscreen=""></iframe>

※ width、heightやiframeのオプションは任意の記述に変更してください。

出力時の記述は一緒ですね。