What is a shortcode in WordPress?
A shortcode is a placeholder that can be used anywhere on a WordPress site to display various components. It is a snippet of code wrapped in brackets that is used to render a specific element/module/ or template. It is formatted as followed:
Many of the popular WordPress plugins and themes - such as Gravity Froms, Memberpress, Learndash, and BuddyBoss - all have their own collections of shortcodes that are available to use; making it easier for web administrators to display various components anywhere on the website.
For example, the Gravity Forms shortcode [gravityform id="1"] will display a Gravity Form with the ID one, and the Memberpress shortcode [mepr-account-info field="first_name"] would display the first name of a logged-in user.
This opens the door for non-coders to easily be able to create dynamic websites. WordPress has a number of native shortcodes that you can use such as [audio], [gallery], and [caption].
Attributes
Attributes allow you to pass specific information, or variables, to your shortcode component. Attributes make your shortcode more dynamic, and allow for a greater deal of customization and unique content. In the Memberpress example above, we can see that the "field" attribute is used to manage what account information to display.
Create Your Own Shortcode
For this wordpress shortcode example, we will be creating a simple placeholder that will display the email of a logged in user. This is useful in many different scenarious where you the user may want to see the email address that they are logged in with.
Later on we will extend this to accept a length attribute, as well as give it some basic options and styles.
Creating a shortcode invovles knowing a little bit of code, using PHP, and knowing your way around the theme files. The PHP code can be placed in your theme's functions.php file or in a plugin.
Here is the basic code snippet you need to create a static shortcode:
Here are a few things to keep in mind:
- The name of your shortcode can be anything. Although not required it's good practice to prefix functions and shortcode names with 3-5 letters so as not to cause any conflicts with other plugins or themes. As you can see in the example above, we have used the prefix "otslr."
- Anything between anything between ob_start(); and return ob_get_clean(); is what will be rendered.
- the $atts, are optional but useful for making it even more dynamic
Now lets make this a tad more dynamic. We want to set a character limit (because emails can sometimes be very long), and we want to use the email of the current logged in user.
To do this, we will use some native WordPress functions
Now let's add some attributes. We want to be able to set whether to display a mailto: link or not.