shopify agency of the year

May 07,2010 Shopify API

Using Short Codes to Easily Format WordPress Page Content

Custom short codes can be extremely useful towards setting up a conveniently manageable WordPress theme design. Since WordPress 2.5, there has been in-built support for creating custom short codes using the add_shortcode() function.

A Basic add_shortcode() Example

In the example below I have used the short code [go] (square brackets are always included as part of a WordPress shortcode) to enter a linked button that could, for example, be used as a link on multiple pages throughout the site.

[realgo]

The advantages in this case are in:

  • speed
  • ease-of-use
  • consistency

You can be assured that the button & link will be consistent whenever the short code is used and the process will be altogether more efficient (provided you remember the short code!).

To set up this short code the following lines were added to functions.php in the theme folder:
function add_go_button() {
return '<a href="https://www.junoecommerce.com/contact"><img src="https://www.junoecommerce.com/wp-content/themes/juno/images/go-button.png" alt="go" /></a>';
}
add_shortcode('go', 'add_go_button');
The parameters used by add_shortcode() are firstly the short code (here 'go' corresponding to '[go]' when entering post/page content) and secondly the function that you want to be called when the short code is processed.

Using add_shortcode() To Format Content Easily

The next example shows how short codes can be wrapped around content, in this case to format a section of text. The content in the admin section is input as:

[box]This content is wrapped in a fancy box.[/box]

This content is then processed to appear as:

[realbox]This content is wrapped in a fancy box.[/realbox]

A key advantage here is that the theme can be set up to allow an editor who is unfamiliar with XHTML & CSS enhanced options for formatting their content - and this is all possible while remaining in 'Visual' (rather than 'HTML') mode in the admin.

The code added to functions.php to enable this short code is:
function fancy_box( $atts, $content = null ) {
return '<div class="fancy">' . $content . '</div>';
}
add_shortcode('box', 'fancy_box');
This post only begins to look at the options available using the WordPress Shortcode API. This functionality can be extended with attributes and nested short codes.