What are WordPress Shortcodes

WordPress offers several ways to add pieces of HTML content to any part of your page. One way to add HTML content is through shortcodes.

A shortcode is a piece of text markup that you can embed anywhere where text editing is allowed. This can be in the post editor, widget areas, or in the source code itself.

Parts of a Shortcode

A WordPress shortcode has two parts – the shortcode name and the attributes. Here is what a Shortcode looks like:

[my_shortcode]

You first add the opening and closing angled brackets, and in between the brackets, you write the shortcode name.

If the shortcode has attributes you add them inside the brackets as well.

[my_shortcode total="4" size="small" ]

Attributes are a way to customise the content to be displayed. For example, a shortcode that shows related posts can have an attribute of the number of posts to show.

To add attributes write the attribute property, followed by an equals sign and the attribute value enclosed in double or single quotes like above.

Benefits of shortcode

Shortcodes allow code reusability. You can add the same HTML content to different parts of your site. You can also add different customisations to the content through attributes.

You can embed shortcodes anywhere there’s an editor.

How to create a Shortcode (for developers)

You create a shortcode with the add_shortcode WordPress function. The function accepts two arguments; the shortcode name and the callback function.

A shortcode to display random tips on a page. Create a txt file with the tips separated by two line breaks like so:

Tip 1

Tip 2

Tip 3

Add the following code into the functions.php file:

function random_tips_generate(){
	$contents = file_get_contents( get_theme_file_uri() . '/media/tips.txt' );
	$list = explode("\n\n", $contents);
	shuffle($list);
	return '<span class="fa fa-lightbulb-on fa-lg"></span> <strong>Tip: </strong>'. $list[0];
}
add_shortcode( 'random_tips', 'random_tips_generate' );