Configure Youtube URL embed parameters with ACF

<h3 class="entry-title">Configure Youtube URL embed parameters with ACF</h3>
Posted on

One of my clients requested that the related videos be disabled at the end of an embedded youtube video. This can be done by editing the URL to include the appropriate parameters but I found that when using the oembed fieldtype that the parameters were being stripped out and lost along the way.  Luckily the documentation for oembed on the ACF website is very thorough and has a code example. From this code example I was able to tweak  it into the template for the custom post type.  From the work I learned  about the php method: str_replace and add_query_arg

add_query_arg will either take a string or an associative array and will build and retrieve a new URL string for the given $src string.

str_replace will take the pattern in the first argument  and replace it with the string in the second argument for as 0 or more occurrences in the third argument which is known as the haystack (in this example it is the complete  $iframe html string )

In the end I decided upon using the parameters rel=0,modestbranding=1 and showinfo=0 to disable the videos and to minimize the amount of clutter on the interface.  Below is a more complete example

    // get iframe HTML
    $iframe = get_field('video');

    // use preg_match to find iframe src
    preg_match('/src="(.+?)"/', $iframe, $matches);
    $src = $matches[1];

    // add extra params to iframe src
    $params = array(
        'rel'    => 0,
        'modestbranding' => 1,
        'showinfo' => 0

    $new_src = add_query_arg($params, $src);
    $iframe = str_replace($src, $new_src, $iframe);

    // add extra attributes to iframe html
    $attributes = 'frameborder="0"';
    $iframe = str_replace('></iframe>', ' ' . $attributes . '></iframe>', $iframe)
    <div class="embed-container">
        <?php echo  $iframe;?>