Last updated May 13th, 2016 at 04:37 pm
In this article, I’ll share a custom PHP shortcode function I use for my non-WordPress Web sites to improve their maintainability. This function mimics the WordPress shortcode feature.
Skip the introductory remarks — take me to the function!
Shortcodes in WordPress
The WordPress shortcode feature has been available for years — since March, 2008, with the release of version 2.5.
Shortcodes in WordPress are shortcut codes (macros, if you will) embraced in square brackets which, when processed by the WordPress parsing engine, automatically and dynamically convert to whatever content (words or phrases — virtually any HTML code, for that matter) is associated with the shortcode.
Some shortcodes are built into WordPress (the [gallery]
shortcode being one of the best-known), but you can create an unlimited number of additional custom shortcodes with just a little bit of PHP, usually in your theme’s functions.php file.
A typical and almost trivial — yet still useful — use case for a custom shortcode would be your company name.
Suppose, for example, that I wanted my full company name (nSiteful Web Builders, Inc.) to appear in bold, italic, navy-blue letters in multiple pages and posts on my site. (Further suppose that I created a CSS style called ‘co-name’ to handle those presentation attributes.)
I could type this everywhere it needs to appear…
<span class="co-name">nSiteful Web Builders, Inc.</span>
…or I could create a shortcode (I might call it [coname]) that converts to the above whenever WordPress processes the page or post in which the shortcode appears.
Kinda nifty, right?
Shortcodes aren’t just good for WordPress
Even though most Web sites I build these days are built on WordPress, not all of them are. Plus, I still maintain a healthy number of Web sites I created before I became a WordPress developer.
Can shortcodes improve the maintainability of non-WordPress Web sites, too?
You bet they can!
The DRY principle
Every Web developer worth his or her garlic salt knows about the DRY principle — and the importance of employing reusable components whenever possible.
The formula for the cost of repeating oneself isn’t linear; it’s geometric. It’s not simply a matter of it taking twice as long to code something twice (or three times as long to code something three times, and so on). It’s a matter of all the time you’ll spend looking for and modifying your code when (that’s right, when, not if) circumstances (such as your clients changing their minds) require changes.
(I won’t lie: I’ve learned this lesson the hard way.)
Some bits of content are repeatable by definition, by their nature. Obvious examples are headers and footers and navigation bars and persistent sidebars and such. For these repeatable content elements, I’ll use includes and database tables and scripts.
For the other stuff, I’ll use PHP shortcode snippets.
Nowadays, whenever I publish content for my custom Web projects, I ask myself, Is it possible that this bit of content will appear in multiple places and would it save me time if I employed a reusable shortcode?
Content that earns a yes
to the above question includes anything that…
- is time-consuming to type
- is prone to misspelling
- must always appear the same way everywhere
- might need to be altered, even slightly, some day
Typical examples:
- specially-formatted names
- abbreviations and acronyms for which the corresponding long text should appear as the value of the title attribute in the abbr tag
- phrases conveying statistics or experience (e.g.,
We serve clients in 32 countries on 4 continents.
)
And now the function
function shortcode($code='coname', $show='term', $before_term='', $after_term='', $echo=true) { switch ( $code ) { case 'coname' : $term = 'nSiteful Web Builders, Inc.'; $abbr = 'nWB'; $before = '<span class="org">'; $after = '</span>'; break; case 'sacs' : $term = 'Southern Association of Colleges and Schools Council on Accreditation and School Improvement'; $abbr = 'SACS/CASI'; break; case 'serve' : $term = '32 countries on 4 continents'; break; } $before_code = ( isset($before) ) ? $before : ''; $after_code = ( isset($after) ) ? $after : ''; $default_output = $before_code . $term . $after_code; switch ( $show ) { case 'term' : $output = $default_output; break; case 'abbr' : if ( isset($abbr) && !empty($abbr) ) { $output = '<abbr title="' . $term . '">' . $before_code . $abbr . $after_code . '</abbr>'; } else { $output = $default_output; } break; case 'both' : if ( isset($abbr) && !empty($abbr) ) { $output = $before_code . $term . $after_code . ' (<abbr title="' . $term . '">' . $abbr . '</abbr>)' ; } else { $output = $default_output; } break; } if ( !$echo ) return $output; echo $output; }
Notes about the function:
The function takes five arguments, each of which has a default value defined in the parameter list:
- $code: The actual shortcode string that I’ll pass in a PHP snippet. Since I expect to use the Company Name (coname) shortcode more than any other, I made this the default. I’m lazy.
- $show: What is it I actaully want to display? The choices are term: the term itelf; abbr: only the abbreviation (if applicable), with the term set as the value of the title attribute of the abbr tag (this will pop up as a tool tip in some browsers); or both: the term with the abbreviation in parentheses.
- $before_term: Any HTML I might want to appear before the term.
- $after_term: Any HTML I might want to appear after the term.
- $echo: A boolean value, indicating whether the function should display or return the output (default: display).
The first switch statement (lines 2-18) evaluates the shortcode itself. Based on the value of that first passed argument, the function defines the set of variables for the output. For every case, a $term variable is defined; all others are optional.
On lines 19-20, I’m using ternary operators to redefine what should appear before and after the term.
Line 21 defines the default output.
The else structures on lines 30-32 and 38-40 are protections against myself. If, somehow, I were to insert a shortcode snippet whose $show value is either 'abbr' or 'both' — and I negelected to define the $abbr value for the shortcode in the first switch statement — the result will degrade gracefully to displaying only the $term.
The second switch statement (lines 22-42) evaluates the 'show' argument and assembles the output accordingly.
Finally, the if statement on line 43 will return the output (and never get to line 44) if the $echo argument is false. Otherwise, the script will continue to line 44 and echo (display) the output.
How to enter shortcode snippets:
And here’s how I would enter the shortcodes:
- To embed this HTML markup…
<span class="org">nSiteful Web Builders, Inc.</span>
…I would insert this code snippet:
<?php shortcode();?>
- To embed HTML for my company name, abbreviated, with the full name as the value of the title attribute of the abbr tag, I would insert this code snippet:
<?php shortcode('coname', 'abbr');?>
- To embed HTML for the The Southern Association (etc.) term and abbreviation, I would insert this code snippet:
<?php shortcode('sacs', 'both');?>
- And to embed this HTML…
<span class="org">nSiteful Web Builders, Inc.</span> serves clients in 32 countries on 4 continents.
…I would insert this code snippet:
<?php shortcode();?> serves clients in <?php shortcode('serves');?>
Conclusion
Shortcodes aren’t just for WordPress. Together with many other PHP Dry tools, they have saved my bacon many times.
Leave a Reply