How to Make a WordPress Shortcode from Scratch

Anthony Corea

If you aren’t already then you should start taking of one of the best tools WordPress gives you, the WordPress Shortcode API. With it you make complex and useful content that is super easy to implement.
So in this short tutorial we’ll take a look at how to make something you could feasibly use on a client’s site, A responsive iFrame. To do this we’ll make a shortcode that will wrap our iFrame in a responsive element.

The goal is to make so that the only thing the user will have to do is insert the embed URL

Copy and paste this code into your functions.php.


function shortcode_embed( $atts, $content = null ) {
extract( shortcode_atts( array(
'link' => ''
), $atts ) );

$output_string = '

<div class="flex"> <iframe src="'. $link .'" style="border:0;" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen> </iframe> </div>

';
return $output_string;
}
add_shortcode('iframe', 'shortcode_embed');

That first value ‘iframe’ will be the name of the shorcode. Feel free to change it to whatever you like.

And copy this CSS into your style sheet.


.flex {
position: relative;
height: 56.25vw;
overflow: hidden;
}

iframe, object, embed {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}

This uses the Viewport Width CSS unit, if you need to support