0

With the following shortcode for YouTube videos, how can I make it such that WordPress still automatically embeds the video for me?

<?  /** YouTube shortcode, usage: [youtube align="alignleft" id="123456789" ] */
    function shortcode_youtube($atts) {  
        extract(shortcode_atts(array(  
            "id"    => '', 
            "align" => 'aligncenter'  
        ), $atts));  
        return '<div class="'.$align.'">http://www.youtube.com/watch?v='.$id.'</div>';  
    }  
    add_shortcode("youtube", "shortcode_youtube");      
?>

What it currently does, is display the url of the video. What I want is it to embed the video (like it would do if I just pasted the video's url into the wp editor).

1 Answer 1

3

There may be a more graceful way to do this, but it works:

function shortcode_youtube($atts) {  
    extract(shortcode_atts(array(  
        "id"    => '', 
        "align" => 'aligncenter'  
    ), $atts));

    global $wp_embed;
    $content = '[embed]http://www.youtube.com/watch?v=' . $id . '[/embed]';
    $embed = $wp_embed->run_shortcode( $content );

    return '<div class="'.$align.'">' . $embed . '</div>';  
}  
add_shortcode("youtube", "shortcode_youtube");

Your Answer

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

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