• Skip to main content
  • Skip to primary sidebar
  • Skip to footer

nSiteful Web Builders

Building a Better Web - One Site at a Time.

  • Home
  • About
    • Testimonials
    • Resources
  • Web Sites
  • Online Marketing
  • WordPress Support
    • Customized WordPress Training
    • 60-for-60 Sessions
  • Web Applications
  • Blog
    • Archive Listing Minimalistic
    • Blog Articles Grouped by Category
    • Case Studies
    • General
    • Portfolio
    • Reviews
    • Snippets
    • Techniques
  • Contact Jeff
    • Purchase Retainer Consulting Hours
    • About Retainer Consulting Hours

By Jeff Cohan, September 30, 2013

Custom extensible PHP shortcode function for non-WordPress Web sites

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

shortcodes-captureThe 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.

Related Posts

  1. Add Dynamic Table of Contents to a Series of WordPress Posts
  2. Diagnostic PHP: Get All Included Files
  3. Diagnostic PHP: Get All User Functions
  4. Why, When, and How to use sprintf and printf
  5. Diagnostic PHP: Get All User Constants
  • Choose the best match.

Written by Jeff Cohan · Categorized: Snippets · Tagged: php, WordPress

  • Choose the best match.

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Primary Sidebar

mailchimp signup

Subscribe to get notified when new articles are published. Unsubscribe any time. No spam. I promise. Check out my newsletter archives.

social

Twitter Facebook LinkedIn

Recent Articles

  • Use Case for Custom Post Type: “In The News” March 10, 2023
  • Create a Custom Shortcode to Display a MemberPress Membership Price ANYWHERE on Your Website February 5, 2023
  • Avoid Direct Styling; Use CSS Instead September 21, 2022
  • Blog Tags: What They Are (and What They’re Not) August 5, 2022
  • How to Create a Simple Custom Events Plugin May 24, 2022

Filter By Category/Tag

Categories

  • Case Studies (7)
  • General (61)
  • Portfolio (5)
  • Reviews (12)
  • Snippets (16)
  • Techniques (38)

Popular Tags

Advanced Custom Fields Blogging Child Themes Content Marketing CSS CSS Grid Customer Service Custom Fields Custom Post Types Diagnostics Facebook FooGallery Genesis Gutenberg HTML Images iPhone Libra Live Chat Marketing Media MemberPress MemberPress Courses mu-plugins MySQL Photo Gallery php Pinterest Plugins Post Formats Pricing Project Management Security SEO Seth Godin Shortcodes Social Networking Surveys Taxonomies Trello Twitter Video Web design Web forms WordPress

siteground wp hosting

Web Hosting

wp101

EasyWordPresstutorialvideosforbeginners.
MemberPress CTA

Footer

Background

Web Sites | WordPress Support | Web Applications.

Formally trained in liberal arts and education (I have a B.A. in Government from Harvard and studied Secondary Education at Rutgers Graduate School), I have honed my skills in the communication arts and sciences as a teacher, trainer, instructional designer, writer, photographer, calligrapher, helpdesk manager, database programmer, and multimedia developer.

(I've also been a group counselor, waiter, bartender, bicycle messenger boy, computer salesman, carpenter's helper, financial analyst, and school board president.)

Tech

Systems since 1983.
Web sites since 1994.
PHP since 2001.
WordPress since 2007.

Contact

770-772-5134
Email Jeff
Send Money
All Ways

Copyright 2023, nSiteful Web Builders, Inc.

 

Subscribe

Pardon the interruption. I know popups can be annoying. But I’d love to have you as a subscriber.

Sign up to be notified when new articles are published. Unsubscribe any time.

* indicates required

Powered by MailChimp

×