Creating Your Own WordPress Shortcode

Shortcodes: An Introduction

What are shortcodes in WordPress? As WordPress.com elegantly says,

A shortcode lets you do nifty things with very little effort. Think of a shortcode as a shortcut to add features to your website that would normally require lots of complicated computer code and technical ability.

When Would I Need to Use a Shortcode?

Often times you’ll find yourself wanting to insert dynamic content into your page. While page builders (such as Elementor and WPBakery Page Builder) do a decent job of offering built-in widgets/elements to do just that, you’ll occasionally find yourself in a situation where those tools simply cannot accommodate your needs. In those instances, shortcodes are often the most simple and direct way to fill that gap.

How Shortcodes Are Used

One of the reasons shortcodes are a simple solution is that they don’t rely on any other plugin such as page builders—they are supported by WordPress itself. In order to use a shortcode, all you need to do is enter a shortcode like [my_shortcode] into any text field.

When WordPress starts to load the page, it’ll recognize that snippet as a shortcode and then execute whatever code is assigned to it. Some shortcodes will support attributes that can be used to change the behavior of the final output. Such a shortcode would look like [my_shortcode attr="value-here"].

What About the Code?

Now that you know how to add a shortcode to a page, the next piece of the puzzle is coding the shortcode. With shortcodes being supported by the core of WordPress, registering a shortcode on the backend is a simple one-liner:
add_shortcode( 'shortcode_name', 'shortcode_output' );

Full documentation on add_shortcode() can be found on the WordPress Codex but, to summarize, the first argument is the name of the shortcode (what you type inside the square brackets) and the second argument is the name of a function that will return the desired content.

Example

In the following example, we already have a custom post type (article coming soon) registered. This CPT is dedicated for “research areas” where each research area is its own post which contains information about it.

While we could manually use the text editor within the page to manually write out the list of research areas, that is a tedious task. Furthermore, if you ever decided to add (or remove) a research area in the future, you’ll have to be sure to go to the page that contains this list and make updates there as well.

So, to automate this process, we created the following shortcode: [research_area cols="X" open="Y"].

The Code

            <?php
// General Purpose: Output list of Research Areas
function output_ra_list( $atts, $content = null ) {

	// Attributes
	$atts = shortcode_atts(
		array(
			'cols' => '1',
			'open' => 'same',
		), $atts, 'research_area' );

	// Build args
	$args = array(
		'post_type'				=> 'research_area',
		'orderby'					=> 'title',
		'order'						=> 'ASC',
		'posts_per_page'	=> -1,
	);

	// Run query
	$research_areas = new WP_Query( $args );

	// Declare output string
	$output = '';

	// Proceed only if there are posts
	if( $research_areas->have_posts() ) {

		// Start list
		$output .= '<ul class="research_areas-list dsa-cols-'. $atts['cols'] . '">';

		// Loop through query
		while( $research_areas->have_posts() ) {

			$research_areas->the_post();

			// Ease-of-use vars
			$ra_link 		= get_permalink();
			$ra_title 	= get_the_title();
			$target			= ( $atts['open'] == 'new' ) ? ' target="_blank"' : '';
			
			// Build output
			$output .= sprintf('<li><a href="%s"%s>%s</a></li>', $ra_link, $target, $ra_title);

		}

		// End list
		$output .= '</ul>';

	}

	// Restore original post data
	wp_reset_postdata();

	// Return count of entries
	return $output;
}
// Register shortcode
add_shortcode( 'research_areas', 'output_ra_list' );
        

* ALWAYS be sure to escape your variables upon output.

The Implementation

Shortcode text example

The End Result