As you already know, WordPress is the most popular CMS in the world. Who would have known a few years ago that today we can really build fully featured and functional websites within minutes? Working with WordPress is a breeze. Not only that it allows you to create gorgeous websites fast, but thanks to the great community which gravitates around it, you`ll find answers and solutions to all of your questions.
WordPress built a bridge between the way we are and the way we work and introduced the all-mighty Shortcodes.
What are shortcodes?
As the name says, shortcodes are simple lines of code which replace more complex functionality. So, instead of writing 50 lines of complex code into a post or page, implementing them into a shortcode allows you to write only one line of code.
Now you might think that building shortcodes is hard. Well, it`s not that hard and requires minimum PHP knowledge. To prove you, I`m going to create a shortcode which allows us to integrate Google Maps into any post/page.
First let`s take a look at the embed code Google provides:
The most important attributes of the code are “width”, “height” and “src”. The first two are giving the map dimensions and the third one is rendering the map found at the url. We`re going to make use of these 3 attributes when building the shortcode.
Any additional code which aims to extend WordPress functionality is added into a file called “functions.php”. If your theme doesn`t have one, create one.
Open your functions.php file and drop the next code into it:
This is how the function looks. The code can be split in two: the main function and the function call. The main function has some parameters which are passed to the shortcode callback function:
- $atts – an associative array of attributes
- $content – the enclosed content (if the shortcode is used in its enclosing form like [shortcode] … [/shortcode]). We set it as null because the shortcode doesn`t use content within its begin and end tags.
If you take a look at the embed code provided by Google, you`ll see that we took it, wrapped it into a class(contact-map) for further styling and implemented into it the function attributes($width, $height and $src).
To use the shortcode, all you have to do is to add into any post/page:
This form will render a google map of 940x300px. To create another map of different dimensions use the extended form:
That`s it! You just implemented Google Maps into a shortcode.
Like other great features WordPress offers, shortcodes are meant to help us and extend the already ultra-extended WordPress system and because is built on PHP, it offers us the flexibility that we need in order to achieve better performances within websites! The key is to start learning it and will become your best friend!