iFrames in WordPress Post Editor Using Shortcodes and Custom Fields

I was looking for a way to embed a Google Map into one of my Reviews, but the FCKEditor, otherwise known as the Visual (or pretty) Editor, would remove any iFrame code. Posting it via the HTML tab works so long as you don’t click to the Visual tab, as it will strip the iFrame code. This can get pretty frustrating. I didn’t want to have to install another plugin to do iFrames either. Fortunately through a quick Google search I found Walt had a very elegant solution using WordPress Shortcodes and Custom Fields.

His technique worked out quite nicely and will allow me to post other iFrame content while still using the Visual Editor and not worry about the iFrame code getting stripped out. So I’m reposting his technique here for future reference.

You need to have a functions.php file in your theme for this to work. If it doesn’t exist, just create one and drop this line of code into it, making sure it is wrapped by <?php and ?> (thanks to Smick for reminding me):

[sourcecode language=”php”]
function field_func($atts) {
global $post;
$name = $atts[‘name’];
if (empty($name)) return;

return get_post_meta($post->ID, $name, true);
}

add_shortcode(‘field’, ‘field_func’);
[/sourcecode]

Upload that file into the theme folder that you are using or want to enable iFrames for.

[showads]

Now any anytime you want to embed a Google Map iFrame, all you have to do in your Post Editor is decide where you want the iFrame to appear and put:

[field name=iframe]

Then scroll down to the Custom Fields box and under Name write iframe and under Value paste in the exact code. Here’s an example:

WordPress-iframe-shortcode-functions-example

Make sure you click Add Custom Field to save the entry or it won’t show up in your post when you publish or update the changes. Now you can easily edit the existing post using the Visual Editor and not have to worry about losing any of your iFrame code.

Also note that unlike a plugin where you can switch themes and the code will continue to work, once you switch to a new theme, the iFrame code will no longer appear in any of your posts so make sure to include this line of code in your new theme. You could also save yourself the headache and make this function into a WordPress plugin.