1

I want to add an id="myid" to shortcode embedded iframe:-

$video_url = get_post_meta($post_id, 'video_url',true);
//or
$video_url .= 'video url';
$check_embeds=$GLOBALS['wp_embed']->run_shortcode( '[embed]'. $video_url .'[/embed]' );
echo $check_embeds;

This code helps me to display video through custom meta box just using a video url. And additionally I want add an ID to iframe here, example:- <iframe id="myid" src=""></iframe>like this. Can anybody help me to fix the issue?

0

1.- Add this to your child theme's functions file:

add_filter("embed_oembed_html", function( $html, $url, $attr ) { 
    if ( !empty( $attr['id'] ) ) {
        $html = str_replace( "<iframe", sprintf( '<iframe id="%s"', $attr['id'] ), $html );
    }
    return $html;
}, 10, 3);

2.- Now use [embed id="myid"] applying the ID attribute in the shortcode.

$check_embeds=$GLOBALS['wp_embed']->run_shortcode(
    '[embed id="myid"]'. $video_url .'[/embed]'
);

Hope that helps.

0

Since you're talking about using an <iframe> to embed the video URL, I decided to take a different approach instead of using WordPress' [embed] shortcode and create my own [iframe] shortcode (add this to your functions.php):

add_shortcode( 'iframe', 'wpse_237365_iframe_shortcode' );

function wpse_237365_iframe_shortcode( $iframe ) {
    $tags = array( // Default values for some tags
        'width' => '100%',
        'height' => '450',
        'frameborder' => '0'
    );

    foreach ( $tags as $default => $value ) { // Add new tags in array if they don't exist
        if ( !@array_key_exists( $default, $iframe ) ) {
            $iframe[$default] = $value;
        }
    }

    $html = '<iframe';
    foreach( $iframe as $attr => $value ) { // Insert tags and default values if none were set
        if ( $value != '' ) {
            $html .= ' ' . esc_attr( $attr ) . '="' . esc_attr( $value ) . '"';
        }
    }
    $html .= '></iframe>';
    return $html;
}

Why not work off of the [embed] shortcode?

The code I provided above not only lets you add your id= attribute, but also any other attributes you plan on adding, giving you much more flexibility.

Shortcode Example 1

[iframe src="https://link.to/video" id="my-id-here" width="100%" height="500"]

Will give you:

<iframe src="https://link.to/video" id="my-id-here" width="100%" height="500" frameborder="0"></iframe>

Shortcode Example 2

You can even make up attributes if need be:

[iframe src="https://link.to/video" scrolling="yes" custom-tag="test"]

Will give you:

<iframe src="https://link.to/video" scrolling="yes" custom-tag="test" width="100%" height="450" frameborder="0"></iframe>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.