How to create a simple shortcode to embed an iFrame in WordPress
I was just asked to add a nice little feature to a client site. Essentially they wanted to embed a copy of their newsletters into blog posts and pages but the CSS of the site was interfering with the content in the newsletter and breaking it. Plus it meant adding code to the editor which is never a good thing.
I decided the best solution would be to use an iFrame to display the content which would not be interfered with by the site CSS as before. Asking the client to remember iFrame code would be a big ask in most cases and so the the way to offer this would be to add a new shortcode.
The solution is simple.. upload the .html file from the newsletter and any accompanying images using the media uploader. Click edit next to the html document and you will see the uploaded URL. Simply take that URL to your post and use a simple shortcode as follows:
[iframe src="http://www.yoursite.com/file_url.html"]
When the page is displayed the iFrame is in place and no coding is required. The code I wrote defaults to 630px by 1500px but you can override it using the following example shortcode:
[iframe src="http://www.yoursite.com/file_url.html" width="700" height="800"]
The Code:
add_shortcode('iframe', 'ag_iframe');
function ag_iframe($atts, $content) { if (!$atts['width']) { $atts['width'] = 630; } if (!$atts['height']) { $atts['height'] = 1500; } return '<iframe border="0" class="shortcode_iframe" src="' . $atts['src'] . '" width="' . $atts['width'] . '" height="' . $atts['height'] . '"></iframe>'; }
Installation
You could do this as a plugin but I found it just as easy in this case to add to the functions.php file in the root of the theme directory.
Finally got my aStore to work after I installed your code snippet in functions.php. First helpful code on getting iframes to work I found in over an hour of searching. THANK YOU!
Many many thanks. I was looking for this. This is most wanted by allot of people.
I was looking to a plugin but this is a far better way.
Thanks
Very helpful, thank you so much!
Thanks man, I battled with plugins for a couple of hours, none worked. You solution did! 🙂
Ya Steve you’re rite. I did the same thing.
How would you make a plugin of this?
I battled with plugins for a couple of hours, none worked.