Shortcodes allow users to add custom functionality or content snippets to pages, posts, and widgets without writing complex code. It is ver useful in the Gutenberg block editor and the Elementor page builder. By wrapping a function in a simple bracketed code like [shortcode]
, you can enhance your WordPress site in diverse ways.
What is a Shortcode?
A shortcode in WordPress is a small piece of code enclosed within square brackets, like [example_shortcode]
. Shortcodes enable users to add dynamic content easily. They are commonly used to insert elements like galleries, forms, buttons, or even complex custom functions into a WordPress post, page, or widget area.
For example, if you’re using a WPForms plugin, you might see a shortcode like [ example wpforms id=”xxx” ]. This shortcode generates the entire user registration form wherever it’s placed. You can insert it in the Gutenberg or Elementor Page Builder editor. It’s very convenient to use.
How to create a simple shortcode in the WordPress website.
The WordPress developer codex has the syntax for a WordPress shortcode. Shortcodes use a specific syntax and can be added to your theme’s functions.php
file or a custom plugin. We recommend you create the shortcode by customizing the WordPress plugin because it would not be affected even the WordPress updates to the latest version.
1. Syntax for Creating a WordPress Shortcode
add_shortcode()
function. The syntax is as follows:
add_shortcode( 'shortcode_name', 'function_name' );
- shortcode_name: The name used to call the shortcode in your content.
- function_name: The name of the function that defines what the shortcode will output.
2. Define the Function
The function should return the content you want to display. The function can also accept attributes (optional parameters) that allow you to customize the shortcode’s behavior.
3. Example: Basic Shortcode Plugin
Here’s an example that creates a shortcode plugin to display a simple message.
Step 1: Create a PHP file simple-shortcode-example.php
Add the code snippet below to the PHP file and save it to the simple-shortcode-example folder.
In this example:
- The shortcode
[hello]
will display the message “Hello, World!” wherever it’s placed on a post or page.
Step 2: Use the Shortcode in Content
To use this shortcode, save the PHP code to a folder and zip the folder. upload the plugin and activate it. When using it, add [hello]
to any post or page. You can insert it either to the Gutenberg block or the Elementor page builder editor.
Conclusion
Shortcodes offer a flexible way to display custom content in WordPress. Define your shortcode with add_shortcode()
, create the associated function, and optionally, add attributes to make it more dynamic.