Cloud Service >> Knowledgebase >> WordPress >> Discover the Steps To Use WordPress do_shortcode
submit query

Cut Hosting Costs! Submit Query Today!

Discover the Steps To Use WordPress do_shortcode

The do_shortcode() function in WordPress allows you to execute shortcodes manually within your theme files or plugins. Here’s how you can use it:

Steps to Use do_shortcode() in WordPress

Understand What Shortcodes Are:

Shortcodes are simple code snippets wrapped in square brackets, like [shortcode], that allow you to execute predefined functionality in posts, pages, or widgets.

Create or Identify the Shortcode:

Before using do_shortcode(), make sure you have a shortcode defined. You can create your own using the add_shortcode() function or use an existing one.

Example: If you have a shortcode [gallery] that displays a gallery, you can use do_shortcode() to output it anywhere in your theme or plugin.

Using do_shortcode() in a Theme File:

Open the theme file where you want to display the shortcode’s output, such as header.php, footer.php, or page.php.

Use the do_shortcode() function to manually insert the shortcode:
php

wordpress

Replace '[your_shortcode]' with your actual shortcode.

Using do_shortcode() in a Plugin:

If you’re developing a plugin, you can use do_shortcode() to trigger a shortcode from within your plugin's PHP functions.

Example:
wordpress

Testing the Output:

After adding do_shortcode() in your theme or plugin, check the front end of your website to ensure the shortcode outputs correctly.

Advanced Use Cases:

You can also pass parameters to the shortcode if it accepts them.
php
wordpress

 

You can embed shortcodes within conditional statements or loops.

Example Scenario

Suppose you have a shortcode [recent-posts] that shows the latest blog posts. To use this shortcode in the footer.php file of your theme, you would add:

wordpress

This will display the recent posts in your site’s footer.

Additional Tips

Escaping Shortcode Output: If you’re using do_shortcode() in an area where content might need escaping, consider using esc_html() or similar functions:
wordpress

Shortcode in Widgets: If you’re adding a shortcode directly to a widget, you often don’t need do_shortcode() since many widgets support shortcodes natively.

 

This should cover most of your use cases with do_shortcode() in WordPress.

Cut Hosting Costs! Submit Query Today!

Grow With Us

Let’s talk about the future, and make it happen!