0
votes

I have started coding a wordpress theme by the way the older contents have a shortcode like ;

[youtube]http://www.youtube.com/watch?v=4MhsnuHvZoI[/youtube]

But, this code generate auto embed area with a plugin. Actually, I dont want to use any plugin in my new project. For this reason, I have created a simple shourtcode like this ;

<?php

    //  YoutubeEmbed

    function youtubekod($atts,$content = null ) {
    return '<iframe width="100%" height="315" src="http://www.youtube.com/embed/'.$content.'?rel=0" frameborder="0" allowfullscreen></iframe>'; 
    }
    add_shortcode('youtube', 'youtubekod');


?>

But, if you check short code return line; you will see what i have tried to do. However, the issue is that how I can get just video id between [youtube] tags ? I 'll be glad with your help.

Thanks.

2

2 Answers

0
votes

try this

function youtubekod($atts, $content="") {
    parse_str( parse_url( $content, PHP_URL_QUERY ), $youtube_id ); 
    return '<iframe width="100%" height="315" src="http://www.youtube.com/embed/'.$youtube_id[v].'?rel=0" frameborder="0" allowfullscreen></iframe>'; 
}
add_shortcode('youtube', 'youtubekod');
0
votes

Try this.

<?php

    //  YoutubeEmbed

    function youtubekod($atts,$content = null ) {

        $url = get_the_content($post->post_content);
        $id=0;
        preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', $url, $matches);
        if(isset($matches[1])) $id = $matches[1];
        if(!$id) {
            $matches = explode('/', $url);
            $id = $matches[count($matches)-1];
        }
        $code = '<iframe width="100%" height="315" src="http://www.youtube.com/embed/{id}?rel=0" frameborder="0" allowfullscreen></iframe>';

        $code = str_replace('{id}', $id, $code);

        return $code;

    }
    add_shortcode('youtube', 'youtubekod');

?>