WordPress is the most popular Content Management System (CMS) on the Internet for building web sites. It is used by over 75 million web sites, with more than 400 million people viewing over 24 billion pages each month. It powers well over a quarter of the world’s web sites. (see the stat details here)
One of the key features that makes WordPress a powerful platform is the use of short codes for extending content and functionality of pages and posts.
How to Create a Simple Shortcode
First go and edit the functions.php of the active template. Appearance > Theme Editor > functions.php file
Add a function, this function will return ‘Hello World’ onto the web page.
Below that function we need to register the shortcode, in our example ‘myshortcode’ is the name of the shortcode and the ‘show_my_shortcode’ is the name of the function to call.
Once you save that, you will then be able to call the shortcode from any post in wordpress. You add it to the post as follows.
Here’s an example on how you will call the post
After updating the post, you can review it on the site and you will see your “Hello World!” message.
Creating a shortcode with attributes
There will be times that you want to call a shortcode and send some information to the underlying function. In that case you need to define the function to have attributes.
To get started, first add the $atts to the funcion call, then below we need to extract the $atts into the $attributes variable.
The $attributes will be an array, so you will need the shortcode_atts (this is a wp function that will combine user attributes) to extract the values. In this case we define two attributes: name and total
You need to define a default value for each attribute. In this case we set the text “defaultvalue” to name and 0 to total. Here’s the final function:
The function will show – “This is a test to display a shortcode. The name is defaultvalue and the total=0. Time=2020/04/07”
If we use the same shortcode without attributes, it will display the default values
This is the result:
Then you could use the shortcode with the attributes to pass in a name and total to be displayed:
Here’s the result:
Shortcodes are a powerful way to extend the functionality of WordPress to customize your web site.