How to Create Custom WordPress Shortcodes for Your Editors

Ideally, WordPress authors should never need to edit raw HTML. You should enable plugins and custom meta boxes which allow the user to configure the page as necessary. Unfortunately, there are situations when it’s difficult or impractical to provide UI tools for widgets, e.g.

  • a widget provides numerous configuration options
  • similar widgets can appear multiple times in the page at any location
  • widgets can be nested inside each other, such as a button overlaying a video within a sidebar
  • a widget’s implementation changes, e.g. you switch from one video hosting platform to another.

WordPress shortcodes are ideal for these situations. A shortcode allows the author to use text snippets such as [mywidget] which includes an HTML component in the rendered page without the need for coding.

Where to Create Shortcodes

Shortcodes are often created to aid custom plugin use so you should place those within the plugin code itself. However, you can also place shortcode definitions within a theme’s functions.php file. It’s possibly more practical to create a separate shortcodes.php file then include it within functions.php:

[code language=php]

Your First “Hello World” Shortcode

A shortcode definition consists:

  1. a function which returns a string of HTML code, and
  2. a call to add_shortcode which binds a the shortcode text definition to that function.

The most basic example…

Continue reading %How to Create Custom WordPress Shortcodes for Your Editors%

Source: Sitepoint