Get first video from the post (both embed and video shortcodes)
The goal is to grab the first video (embed or shortcode) from the post. So we need to check post content if it has embedded videos ( supported by WP ) or [video] shortcodes. Multiple videos and embeds could exist in the single post. If found any - return the very first of them, not depending on order of given patterns to match, but on order they have been inserted into the post.
Here is my progress so far...
This one returns first [video] shortcode. Is there a way to make it look for not only video shortcodes, but for embeds also?
function theme_self_hosted_videos() {
global $post;
$pattern = get_shortcode_regex();
if ( preg_match_all( '/'. $pattern .'/s', $post-post_content, $matches ) array_key_exists( 2, $matches ) in_array( 'video', $matches[2] ) ) {
$videos = $matches[0];
$i = 0;
foreach ($videos as $video ) {
if($i == 0) {
echo do_shortcode($video);
}
$i++;
}
}
return false;
}
add_action( 'wp', 'theme_self_hosted_videos' );
Here's my current progress of a function to return first video embed from the post. Not working as expected, though. Obviously depends on $pattern_array order and maybe on the patterns themselves...
function theme_oembed_videos() {
global $post;
// Here is a sample array of patterns for supported video embeds from wp-includes/class-wp-embed.php
$pattern_array = array(
'#https://youtu\.be/.*#i',
'#https://(www\.)?youtube\.com/playlist.*#i',
'#https://(www\.)?youtube\.com/watch.*#i',
'#http://(www\.)?youtube\.com/watch.*#i',
'#http://(www\.)?youtube\.com/playlist.*#i',
'#http://youtu\.be/.*#i',
'#https?://wordpress.tv/.*#i',
'#https?://(.+\.)?vimeo\.com/.*#i'
);
foreach ($pattern_array as $pattern) {
if (preg_match_all($pattern, $post-post_content, $matches)) {
return wp_oembed_get( $matches[0] );
}
return false;
}
}