I'm using the code below to output a video embed for the latest video:
$args = array(
'numberposts' => '1',
'tax_query' => array(
array(
'taxonomy' => 'post_format',
'field' => 'slug',
'terms' => 'post-format-video'
)
),
'meta_query' => array(
array(
'key' => 'dt_video',
'value' => '',
'compare' => '!='
)
)
);
$latest_video = wp_get_recent_posts($args); // Get latest video in 'video' post format
$latest_video_id = $latest_video['0']['ID']; // Get latest video ID
$video_url = htmlspecialchars(get_post_meta($latest_video_id, 'dt_video', true));
echo '<iframe width="180" height="101" src="'.$video_url.'?rel=0&output=embed" frameborder="0" allowfullscreen></iframe>';
The URL outputs fine in the HTML, but the video doesn't show and I get the following error in the console:
Refused to display 'http://www.youtube.com/watch?v=l4X2hQC32NA&feature=g-all-u&context=G258729eFAAAAAAAAHAA?rel=0' in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'.
Through some searching, I found that this is because the format of the videos is incorrect.
The URL in the error above should be formatted like this: www.youtube.com/embed/l4X2hQC32NA?rel=0
So, I found a way to dynamically change the format with the code below:
$text = $post->text;
$search = '#<a(.*?)(?:href="https?://)?(?:www\.)?(?:youtu\.be/|youtube\.com(?:/embed/|/v/|/watch?.*?v=))([\w\-]{10,12}).*<\/a>#x';
$replace = '<iframe width="180" height="101" src="http://www.youtube.com/embed/$2" frameborder="0" allowfullscreen></iframe>';
$text = preg_replace($search, $replace, $text);
echo $text;
However, I am not sure how I can implement that into the original code so I can change the format of the outputted URL. Can someone show me how I can achieve this?