Shortcode with Attributes

For a variety of reasons, you may not be able to add content directly to the WordPress editor. Maybe it’s funky code that’ll get stripped out, or you want a random quote to show up, or it’s some other kind of dynamic content.

That’s what shortcodes are good for! Here’s a simple one that creates a ‘youtube’ shortcode for embedding videos in your post.

add_shortcode( 'youtube', 'youtube_shortcode' );
function youtube_shortcode( $atts ) {
    extract( shortcode_atts( array('id' => '', 'width' => 480, 'height' => 390) , $atts ) );
    $id = trim($id);
    if (empty($id)) return;
    return '<iframe title="YouTube video player" width="'. $width .'" height="'. $height .'" src="http://www.youtube.com/embed/'. $id .'" frameborder="0" allowfullscreen></iframe>';
}

Used in your post like this: . The width and height attributes will default to 480 and 390 respectively if not specified in the shortcode. Quotes around the attribute value are not required unless your value has a space.

Leave a Reply

Your email address will not be published. Required fields are marked *

%d bloggers like this: