Master the WordPress do_shortcode Function to Enhance Your Site

wordpress do shortcode

Table of Contents

Get up to 50% off now

Become a partner with CyberPanel and gain access to an incredible offer of up to 50% off on CyberPanel add-ons. Plus, as a partner, you’ll also benefit from comprehensive marketing support and a whole lot more. Join us on this journey today!

Want to sweeten your WordPress site by incorporating inline shortcodes? The WordPress do_shortcode function empowers you to insert dynamic content anywhere on your website. It can come in handy for many projects. But how does this work, and how can you utilize it to improve both functionality and user experience on your site?

This article is ready to delineate everything you need to know about the WordPress do_shortcode function. You will learn how to use it as well as its importance and the way plugins leverage shortcodes to extend WordPress features. So whether you are a novice beginner or an advanced-by-practice user of WordPress, being well-versed in the understanding of working with shortcodes is essential for making the best out of your site’s performance.

What is Shortcode in WordPress?

A shortcode is a simple and straight way of adding complex items in posts/pages/widgets for which you don’t have to write HTML, CSS, or JavaScript code in WordPress. A shortcode is a placeholder replaced by dynamic content or functionality once the page renders. Shortcodes are the ones that are enclosed in square brackets like [shortcode], and WordPress takes care of processing them and replacing them with the corresponding outputs during site time whenever the content is displayed.

Shortcodes have been known to majorly serve purposes that include embedded qualities for example forms, galleries, or some other features as given by plugins and themes without extra effort beyond coding, thus making the life of a user quite easy, most especially for non-tech savvy people who wish to have interactive items on a WordPress site.

How Shortcodes Work

WordPress shortcodes are inserted directly into the content areas (posts, pages, or widgets). They can also be used programmatically in the theme files using the do_shortcode function.

For instance, if a gallery wants to appear on a page, simply add the shortcode (gallery), and WordPress will render the gallery for you when loading the page.

Tech Delivered to Your Inbox!

Get exclusive access to all things tech-savvy, and be the first to receive 

the latest updates directly in your inbox.

Common Shortcodes Table

WordPress do_shortcode Function: Meaning

The WordPress do_shortcode function filters the shortcodes you add to any part of your site, whether in the posts, pages, or even widgets. Shortcodes are simple snippets for embedding more complex content with only a few lines of code. Thus, they are essential to adding relatively dynamic features without requiring extensive coding knowledge.

Now, you might ask, “Do plugins actually feature shortcodes?” Yes, they do! This is because most WordPress plugins use shortcodes to achieve these features directly in a non-technical way for users, such as contact forms, sliders, galleries, and so on.

Syntax of WordPress do_shortcode Function

The WordPress do_shortcode function covers the following basic syntax:

WordPress do_shortcode function
  • [your_shortcode]: This would be the shortcode that you wish to process and echo.
  • echo: Enables one to output the result of the shortcode directly to the page.

Passing the shortcode to do_shortcode would take care of processing the shortcode and replacing it with the contents.

Benefits of Using WordPress do_shortcode

These are the benefits of using the do_shortcode() function in WordPress:

1. Dynamic Content Integration

  • Modular Functionality: Shortcodes encapsulate complex features (like forms, galleries, or sliders), making them reusable across different pages or posts.
  • Flexibility for Developers: Use do_shortcode() to embed dynamic content directly into templates or theme files, without rewriting code for each instance. 

2. User-Friendly with Content Editors

  • Empower Non-Developers: Content editors can add dynamic elements (like videos, maps, or social media feeds) using shortcodes, without needing coding knowledge. 
  • Simple content management: Shortcodes have made it easy for editors to control complex content blocks via the WordPress editor, making them work fast while having reduced reliance on developers. 

3. Simplifies Custom Theme and Plugin Development

  • Cleaner Code: WordPress do_shortcode() allows developers to quasi-centralize functionality so that no great amount of code duplication has to take place, thereby improving maintainability of their theme/plugin. 
  • Extensibility: Add complex functionalities (like product carousels, customized displays for posts) easily, without too much interference to overall design of the site.

4. Improvement Site Performance and SEO

  • Fast rendering contents: It allows saving dynamic contents in pages but through shortcodes these are load-on-demand, keeping pages lightweight yet fast at the same time. 
  • SEO Benefits: WordPress do_shortcode() allows you to incorporate interactive content, such as reviews or maps, which could boost user interests and enhance SEO rankings.

5. Better Security and Maintenance

  • Secure Content Handling: This process protects the output by WordPress against security threats through the automatic sanitization of shortcode outputs. 
  • Easier Updates: In one shot, change the functionality of a shortcode without updating multiple page templates.

Using do_shortcode in WordPress

do_shortcode WordPress is being highly used in various sections of your WordPress site, theme files, plugin files, and custom templates. This is how you can use it in a different context:

1. Use of do_shortcode in Theme Files

If you need to add a shortcode right into your theme template files (for example, header.php, footer.php, single.php), then you will use the do_shortcode method.

In case you want to show a gallery inside your theme’s page.php file:

showing a gallery inside your theme's page.php file

The above example will process the gallery shortcode and show images with IDs 1, 2, and 3 on the page.

2. Use of do_shortcode in Custom Post Types

As, for using the do_shortcode in a common manner with regard to the custom post types, if there happens to be a custom post type (like being called “portfolio”), then the shortcode would be part of the template for that post type.

Enhance Your CyerPanel Experience Today!
Discover a world of enhanced features and show your support for our ongoing development with CyberPanel add-ons. Elevate your experience today!

do_shortcode in Custom Post Types

This will show a list of recent posts according to Custom post type.

3. Using do_shortcode in Widgets

There is no automatic processing of shortcodes in text widgets, but you can enable this by adding a filter to your theme’s functions.php file:

adding a filter to your theme's functions.php file

This will allow shortcodes to be processed through widgets, and you can use the following code inside the widget area:

use code inside the widget area

This will display the contact form that was created with Contact Form 7.

4. Use of do_shortcode in Plugins

If you are creating a custom plugin and you want to execute the shortcodes within its PHP files, you can work with them using do_shortcode in just the same way as you would do in theme files. For example, let’s say you are creating a custom dashboard widget, which shows recent postings, in such case the code for it would be:

creating a custom dashboard widget, which shows recent postings,

This will show the recent posts list in the output of the custom plugin.

Troubleshoot Common Problems with WordPress  do_shortcode

There are, of course, some problems that come with the high-powered do_shortcode. Here are some of those common problems and the solutions to those problems.

1. Shortcode Is Not Showing Any Content

Cause: Because the plug-in feature is not getting activated that will create the shortcode or while there is an error in the syntax of the shortcode.

Solution:

  • Verify that the plugin supplying the shortcode is activated.
  • Check the syntax for the shortcode. If it is a custom shortcode, verify that it is properly registered in your theme or plugin.

2. Shortcodes Shown as Plain Text

Cause: If shortcodes are placed in areas where WordPress doesn’t automatically process them, such as in custom fields or widgets, they might appear as raw text instead of being processed.

Solution: 

  • Use do_shortcode() in PHP files to process the shortcode correctly. If using in a widget, ensure shortcodes are enabled by adding add_filter(‘widget_text’, ‘do_shortcode’); in your functions.php file. 

3. Output from Shortcode is Incorrect

Cause: Sometimes, the output for a shortcode may not look as intended because of other plugins or themes, wrong parameters of the shortcode, or required attributes are missing.

Solution: 

  • Test it with no attributes to see if the default output works. 
  • Deactivate other plugins to check for conflicts. 
  • Review the required parameters from plugin or shortcode documentation.

4. Shortcode Not Working After Updating Theme

Reason: It may stop working or return inaccurate results when using the do_shortcode function after updating your theme. This may happen when the structure of the theme gets changed or removes shortcode support.

Solution:

  • Check shortcodes processing code in the functions.php file of your theme.
  • Verify that any of your custom shortcodes in functions.php of your theme still exist, are not altered, or removed.
  • Testing with a default theme, such as Twenty Twenty-Three, will also prove useful in ruling out theme issues.

5. Shortcode Output Delayed or Incorrect in Caching Systems

Reason: It can be if you have activated some cache plugin, server-level cache or CDN (Content Delivery Network) on your website because the cached page version does not allow the shortcode to process properly and it results in getting missing or old content.

Solution:

  • Clear the cache of your caching plugin and CDN.
  • Do not allow caching for dynamic-content pages like contact forms, product pages, etc., where shortcodes are used.
  • If server-side caching is being exercised, interact with your hosting provider about the right caching rules for dynamic content pages.

Best Practices for Using WordPress  do_shortcode()

Use the do_shortcode() function accordingly, as follows:

1. Use Some Shortcode in Templates

The problem with calling do_shortcode() in WordPress template files is that it will slow down page rendering. Each time the page is displayed this way using shortcodes, the execution cost is incurred.

Best Practice: Embed no do_shortcode() within the template files, except in cases of absolute necessity. The shortcode functionality resides within the WordPress content area. It is expected to be invoked within posts, pages, etc.

2. Optimize Shortcodes

Overuse or misusage of shortcodes would lead to degrade the performance especially when the shortcodes are associated with costly database queries/third-party calls.

Best Practices: Ensure that all the shortcodes being used are optimized in their usage and are performance-efficient:

  • Caching the results of shortcodes where appropriate.
  • Avoid querying the database multiple times within a single shortcode.
  • Limit the use of resource-intensive operations especially on high-traffic pages.

3. Sanitize User Input

A shortcode may pose democratic threats (i.e. through XSS attack or SQL injection) because it may take user input.

Best Practice: Always control, validate, and escape user input within your shortcodes. Use WordPress functions such as sanitize_text_field(), esc_html(), or esc_url(). Depending on the context, you may always choose one.

$user_input = isset($atts[‘user_input’]) ? sanitize_text_field($atts[‘user_input’]) : ”;

4. Shortcode Attribute Defaults

When attributes are not present or mismanaged the shortcode simply does not function.

Best Practice: Shortcode attributes should have a default value and handle other necessary cases where they are not set.

shortcode attribute

5. Avoid Nested Shortcodes in Performance-Critical Areas

Nested shortcodes do_shortcode() inside other do_shortcode() produces performance bottlenecks.

Best Practice: Limit the use of nested shortcodes mostly in cases of dynamic content or continuously loaded content. If it is unavoidable to use nested shortcodes, make sure every passed shortcode is well-optimized the same. 

avoid nested shortcodes

6. Cache Shortcode Outcomes at Repeated Views

Shortcodes are the ones that put the load on getting data from the database or heavy processing for every request, and that makes the page load slowly.

Best Practice: Cache the output of the shortcodes, especially if the results aren’t changing frequently (Caching HTML results is with transients).

cache shortcode

7. Filter or action using do_shortcode() sparingly

Using the do_shortcode() function in various filters or actions (like in the_content) can slow the performance or conflict with other plugins.

Best Practice: If using do_shortcode() within content filters or actions, do so with performance considerations. When its use is necessary, do so by prioritizing events, such as using wp_footer or wp_head for script-related or metadata shortcodes. 

using do_shortcode within content filters

8. Avoid Redundant Calls

Multiple calls to do_shortcode() create performance lags during page rendering as it is the same shortcode that is called several times during a page’s lifecycle.

Best Practice: Call do_shortcode() only once per page load for the same shortcode. You can do this by checking whether the shortcode has already been run or cached if needed.

CyberPanel To Use WordPress do_shortcode()

CyberPanel is a popular web hosting control panel and is available to use the WordPress do_shortcode function. 

Step 1: Open the CyberPanel login page

  • Log in CyberPanel
  • Go to the CyberPanel login page using your browser. So the URL seems like below: 
  • https:/your-server-ip:8090 or https:/your-domain.com:8090
  • Enter Login Credentials
CyberPanel Login

Step 2: Access WordPress Installation

Navigate to WordPress Manager:

  • From the CyberPanel dashboard, find the WordPress area on the left sidebar.
  • Click WordPress to open the WordPress management page.
navigate to WordPress Manager

Select Your WordPress Website:

  • The above section lists a summary of all WordPress installations hosted on your server.
  • Locate your desired website for short-code addition and click the Manage button beside it.
select your WordPress Website

Step 3: Access the Plugin File for Editing

Access the Admin Dashboard:

  • On the WordPress management page, click on Admin Panel button. It will direct you to the security admin dashboard of your WordPress-created site.  

Access File Manager:

  • On CyberPanel dashboard left sidebar, click on File Manager under Website section, 
  • Then in File Manager, select home directory, followed by public_html (or the root directory of your WordPress installation).
access File Manager

Now, select home directory and go to public_html

 select home directory and go to public_html

Navigate to the WordPress Theme or Plugin Folder:

To Modify Theme Files: 

  • wp-content/themes/your-theme-name/. 
  • Choose the theme file with which you want to insert the shortcode (for example: header.php, page.php, footer.php, etc).
Modifying Theme files

For Modifying a Plugin File: 

  • Go to wp-content/plugins/your-plugin-name/ and select accordingly.
modifying a Plugin file

Edit the File:

  • In the File Manager, click on the Edit button for the selected file in order to open the code editor.

Step 4: Insert do_shortcode() in PHP File

Shortcode Display Inside PHP Files: 

  • Locate the spot in the open PHP file- be it header.php or page.php- where you want to place the shortcode. 
  • This may involve HTML elements or simply anywhere it is intended for you to find the output of the shortcode.
Shortcode Display Inside PHP Files

Add the following PHP code 

<?php echo do_shortcode(‘[your_shortcode]’); ?> 
  • Replace [your_shortcode] to whatever shortcode you want to run. 

Save the File:

  •  Once you’ve inserted the shortcode, click Save at the top of the editor to implement your changes.

Step 5: Clear Cache (If Applicable)

If there are two-or-three types WordPress caching, like that from a caching plugin, or through server-sided caches like that from CyberPanel, the best practice implies clearing the entire cache as an immediate effect of change. 

Clear WordPress Cache: In case one is using a caching plugin such as W3 Total Cache or WP Super Cache:

  • Access WordPress Dashboard from one’s browser.
  • If caching plugins were to be activated, then an additional option would be shown under plugin settings menu, purging or clearing cache.
clear WordPress cache

Step 6: Validation of Shortcode

Front-End Testing:

  • Open the page where you have inserted a shortcode (for example, home or one specific page). 
  • Verify that the shortcode is rendered properly.
  •  You would be able to see the output from it: for instance-gallery, form, or other output.

Error diagnosis:

If Shortcode does not work:

  1. Ensure, in the WordPress editor, that the Shortcode is proper and works.
  2. Make sure to save the PHP file after putting the code in place.
  3. Check Server or WordPress Logs for any exception caused by Shortcode or issues in PHP.
  4. Keep the WordPress site up-to-date because sometimes outdated themes or plugins can cause problems.

Alternatives to Using WordPress do_shortcode() 

do_shortcode() is the primary function used to render shortcodes in WordPress. However, it has several other ways of replicating that action with an additional feature or even control. The following are:

1. apply_shortcodes()

  • Description: The output for the processed shortcode is returned with no echo.
  • Application: Allow use or manipulation of data returned through the shortcodes prior to display.
apply_shortcodes()

2. Direct Function Calls

  • Description: Call the actual function of the shortcode directly without going through the shortcode system.
  • Application: This should be used when one needs more control over the logic and would not like to get through the shortcode handler.
Direct Function Calls

3. Template Includes

  • Description: Include custom PHP templates instead of shortcodes to render dynamic content.
  • Use case: Best suited for rather complicated dynamic content and don’t need shortcodes to process them.
Template Includes

4. Shortcode_exists() Check

  • Description: Ensures the shortcode has been registered before trying to process it.
  • Application: To avoid errors verifiable that would happen through do_shortcode() or apply_shortcodes() method call. 
Shortcode_exists() Check

5. Define Custom Rendering Functions

  • Description: This basically defines custom PHP functions that would render dynamic content.
  • Application: It has flexibility when shortcodes are not required, and one would want to implement custom logic to control content presentation. 
custom rendering functions

These afford flexible and different control over the rendering and processing of dynamic content based on individual needs or the complexity of the project.

Helpful Resources for WordPress Users

How to Launch a WordPress Website by HubSpot

Mega WordPress cheat sheet by Hostinger

FAQs for WordPress do_shortcode()

1. What is the use of do_shortcode() in WordPress?

WordPress do_shortcode() is the function that takes a string containing shortcodes or, even a user-defined tag, as input and returns the entire string with shortcodes converted. Shortcodes are tags that can be used to insert parts of a post, page, or template in order to show some dynamic content as well as build up something complex without writing long blocks of code (like forms or galleries or other custom elements).

2. How will do_shortcode() work to render a shortcode in a template?

WordPress do_shortcode() usage in any of your theme or plugin files allows you to process shortcodes and show their output straight away; we can use this to add gallery shortcodes into a template:

echo do_shortcode(‘‘);

3. Can I use do_shortcode() to execute shortcodes in plugin custom files?

Yes, you can use do_shortcode() in any custom plugin or theme file to convert shortcodes. This lets you add the dynamic content made via shortcodes directly into the PHP code of your plugin, just like you would in posts and pages.

4. Does do_shortcode() apply to processing shortcodes in a widget or for a custom post type? 

Yes. Such processing can be done using do_shortcode() in any widget, custom post type, or any custom content area. Verify, however, that the context within which do_shortcode() is being used, such as a widget or custom post type, allows for shortcode processing since it might differ among widgets or themes.

5. Do plugins have shortcodes in WordPress?

Yes, given that several plugins for WordPress come with shortcodes, enabling the user to easily put dynamic content or features into posts, pages, or widgets. For example, most gallery plugins, form plugins, eCommerce plugins, social sharing plugins, and others provide their users with these predefined standard shortcodes such as [contact_form] and [product_display]. These predefined shortcodes are processed by do_shortcode() in their content. You can also create your own custom shortcodes in your plugin using the add_shortcode() function.

Grand Finale

Make Your WordPress Site Better with do_shortcode()

Understanding the do_shortcode() function allows for seamless integration of dynamic content into your site, enhancing functionality and improving user experience. Whether for forms, galleries, or other custom elements, shortcodes turn many tasks, which would otherwise have been complex, into easily manageable site functions.

Integrating “do shortcode WordPress” with CyberPanel has never been easier because it provides quick modifications to theme or plugin files. It also has an easy-to-understand interface, which means handling all those features of WordPress portal will be made simple.

Go ahead and get started with do_shortcode() so that you can impress your users with your WordPress site!

Hasib Iftikhar
I'm Hasib Iftikhar, a dedicated technical writer at CyberPanel, joining the team in July 2024. With three years of extensive experience in content writing, I specialize in copywriting, article writing, guest posting, affiliate content writing, and SEO. My expertise ensures that each piece of content I create is engaging, informative, and optimized for search engines, helping businesses enhance their online presence and reach their target audience effectively.
Unlock Benefits

Become a Community Member

SIMPLIFY SETUP, MAXIMIZE EFFICIENCY!
Setting up CyberPanel is a breeze. We’ll handle the installation so you can concentrate on your website. Start now for a secure, stable, and blazing-fast performance!