Currently reading: The Runaway Jury by John Grisham

WordPress shortcodes don't need fully-qualified parameters

In other words, you don't need to do something like this…

[fa type="regular" icon="dumpster-fire"]

…because the shorter way will work just fine. Instead of a named array, the passed parameters will simply be a standard numerically-indexed array ⸺ i.e. a "list" in PHP parlance.

[fa regular dumpster-fire]

Nice, eh? All you have to do is account for one or more of the parameters being missing to cover the various output scenarios. For our Font Awesome icon example here, we don't need to require the "regular" bit, so if only one parameter is passed, we know "regular" is intended.

$icon = function ($atts) {
	if (empty($atts)) return;

	switch (sizeof($atts)) {
		case 1 :
			$type = 'regular';
			$icon = $atts[0];
			break;

		case 2 :
			$type = $atts[0];
			$icon = $atts[1];
			break;

		default :
			$type = array_shift($atts);
			$icon = array_shift($atts);
			$rest = ' ' . implode(' ', $atts);
	}

	return sprintf('<i class="fa-%s fa-%s%s"></i>', $type, $icon, (isset($rest) ? $rest : ''));
};

add_shortcode('i', $icon);
add_shortcode('fa', $icon);

The default stuff is more complicated than is strictly necessary, but it's nice because it allows us to send more than two parameters at the shortcode. The rest of them will be added as extra classes to the icon element markup to be targeted by CSS.

What we have in the end is a shortcode that can take from one to n parameters, and each of them finds a use one way or another.

Leave a comment

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