VividVisions

by Walter Krivanek

WordPress: Add iframes to your post using custom fields and shortcodes

The visual editor of WordPress (TinyMCE) loooves to remove iframes from the content. This can be extremely annoying when you want to add Google Maps or other iframe-based widgets to your post. There are several approaches to a solution:

  • Turn off the visual editor
    No problem for someone who has a good grasp of HTML. Not quite a solution, more of a workaround.
  • Edit the TinyMCE configuration files
    The required changes are simple but could be lost with the next update of the editor.
  • Use plugins
    I’m sure, there are tons of WordPress plugins which address exactly this issue but more plugins also mean more maintenance. Especially, when there is a much simpler solution.

Add the following code to the functions.php file of your theme:

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');

Now you can display the value of a custom field in your post by adding the shortcode [field name=name-of-your-custom-field] to your content at the position where you would like it to be shown. Just make sure that the shortcode stands alone on a line, otherwise WordPress would wrap it in a paragraph, which would result in invalid HTML.

To add an iframe, simply paste the HTML code into the ”value” area of your custom field, like shown here:

Wordpress field function

Voilá. Your iframe (or any other HTML code for that matter) will not be removed from your post and you can edit the code without having to switch to the HTML mode.

Update: You’ll need at least WordPress 2.5 to be able to use shortcodes.