How to add shortcodes in WordPress

How to add shortcodes in WordPress

Do you want to include shortcodes on your site? You’ve come to the right place. In this guide, we’ll show you how to add shortcodes in WordPress and show you some examples so you can make the most of them.

Since shortcodes were added to WordPress in version 2.5, users have been using them to achieve all kinds of customization. Shortcodes are very useful and they allow us to run a specific piece of code in posts, pages, and nearly anywhere on our websites. On top of that, they are very easy to use even for the most inexperienced users.

What are shortcodes?

A shortcode will trigger a piece of code specified by the name of the shortcode, which is always enclosed with square brackets like this :  [shortcode-name]

The code that each shortcode runs depends on how the shortcode was created. Many plugins provide their own shortcodes and WordPress also includes some by default. And the best part is that the WP shortcode API allows you to create your own custom shortcodes.

Shortcodes are a great tool for developers because they allow you to insert any script anywhere on your site. When you use the same script many times, you can simply use the same shortcode without having to repeat the code. This helps you save time and keep your code clean.

Additionally, a shortcode can take some values, which work similarly to the parameters of the functions.

[shortcode val1=’hi’ val2=’ok’]

And also can be used as an HTML tag when opening and closing shortcodes like this [shortcode]some text [/shortcode].

In summary, a shortcode lets you run a PHP script on the front end without writing any code (if it’s an existing shortcode). WordPress and some plugins have some shortcodes by default but you can also create your own ones depending on your needs.

Finally, there are different types of shortcodes: to insert galleries, WooCommerce products, forms, images, and much more. Each shortcode is different and does different things.

If you need more information, have a look at this complete guide about shortcodes.

Now that we better understand what they are, let’s see how to add shortcodes to your WordPress site.

How to add shortcodes in WordPress

Before we start, it’s important to note that as each shortcode is built differently, they can have values or not. These values are specific for each shortcode and they pass the values to the code to get the result we want.

As we mentioned before, there are different types of shortcodes, and the WooCommerce shortcodes are some of the most common ones. For example, the [woocommerce_cart] shortcode will display the WooCommerce cart wherever you paste it.

To test it, simply paste the shortcode on a post or page or type it like this: [woocommerce_cart]. Then, have a look at the frontend and you will see the WC cart right where you inserted the shortcode.

NOTE: As we’ll edit some core files, before we start, we recommend you do a full backup of your site and create a child theme. You can create one programmatically or by using any of these plugins.

Add WordPress shortcodes with values

Now let’s use the default gallery WordPress shortcode to learn how to add shortcodes with values.

The gallery shortcode displays a nice-looking image gallery and supports several values. You need to include the ID value to specify which images you want to display in the gallery.  This parameter takes the IDs and displays those specific images.

For example, if we want to display the images with IDs 720, 729, 731, and 732, we add the shortcode to a post or page as follows: [gallery ids=”729,732,731,720”]

To test it, simply paste the shortcode replacing the image IDs with your own IDs. If you don’t know your image IDs, open them in the media library editor and you’ll see the ID on the browser URL and permalink printed on the details of the image.

Add shortcodes in WordPress - Image ID in media library

If you are using the classic text editor, you can simply paste the shortcode into the content. On Gutenberg, on the other hand, you can use the shortcode block. Additionally, many page builders and themes include some other shortcode management solutions that you can use.

Gutenberg

Gutemberg shortcode block

 

Classic editor

Insert shortcode in classic editor

After you add the shortcode, check your site’s frontend and you should see something like this:

WordPress gallery shortcode

Using shortcodes in template files

Another way to use WordPress shortcodes is to add them to the template files. If you want to develop a custom solution, this is an interesting option for you. For example, this allows you to run a shortcode on a logic conditional or change shortcode values dynamically, among many other possibilities.

You can use shortcodes in a template file with the do_shortcode() PHP function. This is a default WordPress function that you can use in any file.

To run a shortcode from a file, simply add the following:

echo do_shortcode(‘[gallery ids=”21,42,32,11”]’);

Now customize the header and run the gallery shortcode in the header.phpfile. To do this, you need to overwrite this file using a child theme. For more information on how to customize templates, check out this guide.

In your WordPress dashboard, add the shortcode to your header, by going to Appearance > Theme Editor, and opening the header.php file. Go to the end of the file and paste the code as shown below:

Shortcode on template file

After including the above script in the file, you will see the gallery in the header.

Using Shortcodes with WordPress hooks

Another way to add shortcodes to WordPress programmatically is to use them in combination with hooks. If you aren’t familiar with hooks, we recommend you check out this guide to learn more about them.

To use a shortcode with hooks you need the do_shortcode() function, just like we saw in the previous section.

The following script will work on the functions.php file of the child theme. We use the wp_footer() hook, so this will be printed on the footer of the site.

/* Shortcode with wp_footer hook*/
add_action('wp_footer','QuadLayers_footer_shortcode');
function QuadLayers_footer_shortcode(){
echo do_shortcode('
[products ids="623"]');
}

This shortcode comes with WooCommerce by default and it’s used to display products. In this case, we’re using it to display a single product, with ID = 623.

Using Shortcodes with WordPress hooks

For more information on how to customize the footer on your site, check out this guide.

How to create custom shortcodes in WordPress

Another interesting alternative is to create your own custom shortcodes. This isn’t hard but it requires some basic developer skills and some coding knowledge. If you aren’t an advanced user, don’t worry. Even the most inexperienced programmers will find this pretty easy.

WordPress provides us with the add_shortcode() function to build and add our own shortcodes. Let’s see how to use this function to create a custom shortcode with some sample scripts.

Display a different message for logged in and logged out users

The following script will create a shortcode and print a message to users. To make it more interesting, we’ve applied a condition to display different messages for logged-in and logged-out users.

/* Shortcode logged-in*/
add_shortcode('loggedin','QuadLayers_shortcode_loggedin');
function QuadLayers_shortcode_loggedin($atts){
    if(is_user_logged_in()==true){
        $response='you are logged in';
    }
    else{
        $response='you are logged out';
    }
return $response;
}

Using an if, we check if the user is logged in and display the message “You are logged in” if it’s true and “You are logged out” otherwise.

How to create custom shortcodes in WordPress

Display a single post by ID

Another option is to add a WordPress shortcode that displays a specified post that we are going to pass as a value in the shortcode.

add_shortcode('get-post','QuadLayers_shortcode_post');
function QuadLayers_shortcode_post($atts) {
    $a = shortcode_atts( array('id' => '',), $atts ); 
    $args = array('post_type' => 'post','p' => $a['id']); 
    $query = new WP_Query($args); 
    $query->the_post();
    $string = '<h3>'.get_the_title().'</h3>' ; 
    $string.=the_post_thumbnail();
    $string .= get_the_content();
    return $string;
}

In this example, we’ve added the shortcode [get-post id="483"]and it looks like this:

Display a single post by ID

Run different shortcodes on a logic condition

In this example, we are going to create a custom shortcode to run different shortcodes on a logic condition.

Our custom shortcode will display different forms that were created with a contact form plugin. So we’ll print a different form for logged-in and logged-out users.

add_shortcode('show-form','QuadLayers_custom_shortcode');
function QuadLayers_custom_shortcode(){
    if(is_user_logged_in()==true){
        $response='<h3>Contact us</h3>';
        $response.='[wpforms id="1374"]';
    }
    else{
        $response='<h3>Subscribe to our newsletter</h3>';
        $response.='[wpforms id="1373"]';
    }
    echo do_shortcode($response);
}

Once again, we use a conditional if to check if the user is logged in or not and display a certain form based on that.

Run different shortcodes on a logic condition

Notes

  • Always return the data when creating a shortcode. If you echo it, you might encounter some issues related to the position you should display the content
  • The do_shortcode(); function works great in most template files, but as it needs to be echoed, it also might trigger some issues
  • Many plugins provide shortcodes that you can use freely. However, some shortcodes might not work on posts, pages, or when trying to use them on the header, footer, or sidebar widgets. This depends on how complex the shortcode is and how it was built
  • If you see some errors when using a custom shortcode on the Gutenberg editor, that means your shortcode is not compatible with Gutenberg. It will work anyway on the frontend and you can try switching to the default editor to get rid of this error

Conclusion

In summary, shortcodes are useful tools that allow you to run a specific piece of code anywhere on your site. When you use the same script several times, you can create a shortcode and use it to avoid repeating the code over and over again. Shortcodes are easy to use even for beginners and help you save time.

In this guide, we’ve seen different ways to add shortcodes in WordPress. We’ve learned how to use shortcodes with values, in template files, and with hooks. On top of that, we saw how to create custom shortcodes and gave you a couple of sample scripts that you can adjust depending on your needs.

To learn more about shortcodes and how to customize your site, check out the following posts:

Have you added shortcodes to your WordPress site? Did you have any issues following this guide? Let us know in the comments below!