The first step is to create the shortcode. To do this, either access your theme’s functions.php (wp-content -> themes) file and place the following code in it or create a custom plugin for WordPress.
Building a Custom Plugin
NOTE: If you are likely to change your theme in the future, it is recommended going through the following steps first to ensure your plugin will not be overwritten by creating a custom plugin for WordPress (e.g. when updating the theme):
- Navigate to *Wordpress Installation Directory* -> wp-content -> plugins
- Create a folder called “my-custom-plugins”
- Inside the new folder, create a file called “my-custom-shortcodes.php”. This file will contain the code of your custom plugin, which in this case will be the code for the
shortcode
- Paste the following code in the file:
- The above code snippet contains the name of your custom plugin and other important information that needs to be provided for WordPress to recognise it as a plugin
- Navigate to Plugins from your WordPress dashboard and locate your custom plugin:
- Click on ‘Activate’ to activate the plugin.
For this demonstration, we are going to create a shortcode which accepts text and a URL.
Edit functions.php
Paste the following code at the end of your WordPress installation’s functions.php file or custom plugins file.
In the above code snippet, we have created a function called ‘call_to_action_shortcode’.
add_shortcode( ‘call-to-action-shortcode’, ‘call_to_action_shortcode’ );
This piece of code tells WordPress to create a
[call-to-action-shortcode]
shortcode (the first parameter passed in the add_shortcode function). The second parameter designates the function that will be called when this shortcode is called in any post or page.
Preparing the CSS
Now that WordPress knows what to return when our shortcode is called, we need to style the text that is being passed. The CSS used for this example is shown below:
Place this piece of code at the bottom of your theme’s style.css file and save it. You can access this file by navigating to Appearance -> Editor -> Style.css in your WordPress installation’s dashboard.
Using the shortcode
We are going to use the shortcode we just created to style a piece of text “Learn More” in a blog post. Place the following shortcode in your post:
Go ahead and preview the post and you should be able to see the following result with the help of the WordPress button shortcode you just created:
That certainly looks better than a Spartan text link, and it catches the attention of every reader on your website! Have you tried to click it? The button below is the real deal.