• 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
    • Partner With Me
    • Frequently Asked Questions
  • Web Sites
  • Online Marketing
  • WordPress Support
    • Customized WordPress Training
    • 60-for-60 Sessions
  • Web Applications
  • Blog
    • At-A-Glance
    • Blog Articles Grouped by Category
    • Case Studies
    • General
    • Portfolio
    • Reviews
    • Snippets
    • Techniques
  • Contact
    • Purchase Retainer Consulting Hours
    • About Retainer Consulting Hours
    • Book a Meeting with Jeff
    • Tell Me About Your Web Project
    • nSiteful Newsletter Archives
    • nSiteful Rewards

By Jeff - 9/30/2013
Cats: Snippets · Tags: php, WordPress

snippets

PHP Shortcode: Custom extensible PHP shortcode function for non-WordPress Web sites

Last updated May 9th, 2024 at 02:59 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.

Like what you see? Share with others and join my mailing list. No long-term commitment, unsubscribe any time.

Related Posts

  1. Avoid Direct Styling; Use CSS Instead
  2. Hayes Shutters Online Ordering System
  3. Help Your Blog Readers Find What They’re Looking For with the Search & Filter Plugin
  4. PHP: Get All Included Files
  5. PHP: Get All User Functions

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

  • Custom MemberPress Pricing Pages December 19, 2025
  • CSS Data Attribute Override December 11, 2025
  • MemberPress Rules Using Custom Taxonomies and Custom Roles December 10, 2025
  • WP Staging Plugin: a First Look November 21, 2025
  • How to overlap elements with HTML and CSS (Grid) only August 13, 2025

Filter By Category/Tag

Categories

  • Case Studies (8)
  • For Staff (1)
  • General (72)
  • Portfolio (7)
  • Reviews (14)
  • Snippets (23)
  • Techniques (52)

Popular Tags

Advanced Custom Fields Blogging Child Themes Content Marketing CSS Customer Service Custom Fields Custom Post Types Diagnostics Domain Names Facebook FooGallery Genesis Hosting HTML Images iPhone Libra Live Chat Marketing Media MemberPress MemberPress Courses Membership Sites Mobile-Friendly MySQL Photo Gallery php Pinterest Plugins Post Formats Pricing Project Management SEBA SEO Seth Godin Shortcodes Social Networking Surveys Taxonomies Twitter Video Web design Web forms WordPress

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

Book Meeting
770-772-5134
Email Jeff
Send Money
All Ways

Copyright 2026, nSiteful Web Builders, Inc.

Cookies Consent
To provide the best experiences, we use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us to process data such as browsing behavior or unique IDs on this site. Not consenting or withdrawing consent, may adversely affect certain features and functions.
Functional Always active
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
Preferences
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
Statistics
The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
Marketing
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.
  • Manage options
  • Manage services
  • Manage {vendor_count} vendors
  • Read more about these purposes
View preferences
  • {title}
  • {title}
  • {title}
https://iframe.mediadelivery.net/embed/392008/42d18bc1-2adc-4741-b733-053d08d09c32
https://vz-000c5976-3ab.b-cdn.net/42d18bc1-2adc-4741-b733-053d08d09c32/play_720p.mp4

Receive occasional emails from Jeff