0

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?

1 Answer 1

1

Like this:

$video_url = "http://www.youtube.com/watch?v=l4X2hQC32NA&feature=g-all-u&context=G258729eFAAAAAAAAHAA?rel=0";
$search  = '#(?:href="https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com(?:\/embed\/|\/v\/|\/watch?.*?v=))([\w\-]{10,12}).*$#x';
$replace = "http://www.youtube.com/embed/$1";
preg_match_all($search, $video_url, $matches);
$embedded_video_url = preg_replace($search, $replace, $video_url) ;
echo '<iframe width="180" height="101" src="'.$embedded_video_url.'" frameborder="0" allowfullscreen></iframe>';

Simply use your own $video_url

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. I had to get rid of http:// in the third line because it was adding it unnecessarily like this: http://http//www.youtube.com/embed/l4X2hQC32NA But now it's working.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.