Hello! This is Pavel. And first, I’d like to apologize for not posting as often as I’d like. Unfortunately (or maybe not), I’ve been very busy with work lately and don’t have time to write new articles. But as long as WordPress remains popular — articles will keep coming, at least once a week.
So, I decided to publish a series of articles dedicated to shortcodes. It’s a well-worn topic, and I’m sure you can find similar posts in almost any WP blog. But it wouldn’t be right to start with “advanced” stuff without explaining the basics. That’s why this first post is focused on the foundations and simple examples. In future articles, we’ll try to combine shortcodes with a module from one of the previous topics.
A shortcode (as I understand it) is a custom BB tag you can insert into a post, page, or template, and which gets replaced with dynamic content programmatically.
I may not be great with definitions, but that’s how I see it. Below I’ll try to explain why.
Examples of shortcodes:
[my-short-code] — “empty” shortcode
[sh color="red"] — shortcode with an attribute
[some_text size="20px" style="bold"]some content[/some_text] — shortcode with attributes and enclosed content
That about covers the variations.
There are many use cases. The first that came to mind was injecting ad blocks — more on that in later posts. For now, let’s look at simple “Hello World” style examples.
Example one. Instead of a shortcode, we want to show a greeting at the beginning of each article. The id attribute selects which message to use.
Shortcode: [hello id="x"], where x is the index of the greeting.
Insert this into your functions.php file:
function wp2fl_hello($attr)
{
$ar = array(
'Hello, it's ...',
'Hello, it's ...',
'Greetings, it's ...',
'I'm glad to see you again on my site ...',
'And again I ...',
'Etc. etc.',
);
return isset($ar[$attr['id']]) ? $ar[$attr['id']] : array_shift($ar);
}
add_shortcode('hello', 'wp2fl_hello');add_shortcode registers the shortcode. The function can take two parameters: attributes and (optionally) enclosed content.
To test it, just add [hello id="2"] to a post and check the frontend.
Example two. Displaying a random image via shortcode [rand-img]:
function wp2fl_rand_img()
{
$ar = array(
'/_images/1.jpg',
'/_images/2.jpg',
'/_images/3.jpg',
'/_images/4.jpg',
'/_images/5.jpg',
);
$i = rand(0, sizeof($ar)-1);
if(isset($ar[$i]))
{
return '<img src="'.$ar[$i].'">';
}
return '';
}
add_shortcode('rand-img', 'wp2fl_rand_img');Example three. Using a shortcode to wrap text in styles — red and bold:
function wp2fl_style($attr, $content)
{
return '<span style="color:red; font-weight:bold">'.$content.'</span>';
}
add_shortcode('style', 'wp2fl_style');As before, insert the shortcode into a post and check the frontend.
That’s it for now.
In the next article, I’ll explain how to use a shortcode to fetch an RSS feed from another site and display it in your content.
