Adding ?enablejsapi=1 to YouTube iframe Code

I have a WordPress site and I have a custom field which holds YouTube iframe codes. There is a string holding these iframe codes named $embed. Videos are displayed in the theme with code:

<?php print($embed); ?>

I want to convert my standard YouTube embed codes such that:

Read More

Standard Youtube Embed Code:

<iframe width="560" height="315" src="https://www.youtube.com/embed/uxpDa-c-4Mc" frameborder="0" allowfullscreen></iframe>

Converted Format:

<iframe width="560" height="315" src="https://www.youtube.com/embed/uxpDa-c-4Mc?enablejsapi=1&html5=1" frameborder="0" allowfullscreen id="video"></iframe>

Simply, I want to add ?enablejsapi=1&html5=1 to end of URL and add id=”video”.

How can i obtain this iframe code by manipulating the parameter $embed?

Tnx.

Related posts

1 comment

  1. This will add the extra params to the source. (Replace with your current print($embed) code.

    // use preg_match to find iframe src
    preg_match('/src="(.+?)"/', $embed, $matches);
    $src = $matches[1];
    
    // add extra params to iframe src
    $params = array(
        'enablejsapi'=> 1,
        'html5' => 1
    );
    
    $new_src = add_query_arg($params, $src);
    $embed = str_replace($src, $new_src, $embed);
    $embed = str_replace('></iframe>', ' ' . $attributes . '></iframe>', $embed);
    
    print($embed);
    

Comments are closed.