WordPress shortcodes are extremely useful for inserting custom content without having to manually type them in every time. You can basically run almost any PHP code almost anywhere on your WordPress website that supports a shortcode. Below is an example of a code snippet that creates a simple shortcode that outputs the string “Hello World!”. Inside the function, you can place whatever you want as long as it is a working piece of PHP code.
Usage
- To implement custom functions anywhere on your website without having to edit your template files.
- Easily organize your code by making them into readable shortcodes which can be inputted in template files as well as inside post content.
- Add code inside your website where PHP codes are not supported. WordPress will grab the shortcode and run the PHP scripts behind the scenes.
- You can use shortcodes for almost anything done via PHP. For example, you can add a simple button with styles, or an amazing slider with your post content in it.
Code
// Create a WordPress Shortcode
function wpt_simple_shortcode() {
echo 'Hello World!';
}
add_shortcode('my-shortcode', 'wpt_simple_shortcode');
Inserting [my-shortcode]
will return ‘Hello world!’. You can replace it with any value that you want to call the shortcode.
A word of caution. Make sure that the code inside the function doesn’t have any bugs and runs properly. If not, you will end up with a broken website wherever you inserted the shortcut.
Explanation
- Just a comment.
- Creating a function
wpt_simple_shortcode
. - Returning the content of our shortcode. In this example, we are using a simple return echo statement that outputs ‘Hello World!’ wherever you insert the shortcut. You should change it to a working piece of code that you can use inside your WordPress website.
- Closing the function.
- Adding our shortcode ‘
my-shortcode'
to run the code inside thewpt_simple_shortcode
function using the built-in WordPress functionadd_shortcode
. You should changemy-shortcode
to whatever you want to type inside the [ and ]. In this example, the shortcode will execute only if you use[my-shortcode]
on your website.