How to use do_shortcode in WordPress (PHP)

Shortcodes in WordPress give you additional functionality and allow you to embed content in pages, posts and sidebars. Many plugins and themes use shortcodes and allow users to dynamically add content to their blog. To better show how shortcodes work, let’s take as an example shortcode of WpDevArt contact form plugin. Here is the shortcodes of WpDevArt contact form:

As you can see, it’s very simple. We have the WpDevArt contact form macro in square brackets. The macro generated by the plugin. WordPress will replace the macro with the content that the PHP function will generate. If we add a shortcode to the post, page, then WordPress will show you the contact form.

But what if you need to use WordPress shortcodes in theme files(Php files)? In this case, you can use the WordPress do_shortcode function.

Let’s go and see how to use the function WordPress do_shortcode.

Using the WordPress do_shortcode function

Now that you have caught the basic idea of using shortcodes in WordPress, let’s see how you can use shortcodes to improve the functionality of your site on WordPress. For example, you need to insert the WordPress plugin in somewhere in the footer of your theme. But the problem is that you do not have any widget in this area.

First of all, you need to take the shortcode of the plugin that you want to use. As an example, we will use the same plugin shortcode – WpDevArt contact form.

First of all, go to the WordPress admin panel and click on Wpdevart Forms.

Then go to forms page and copy the shortcode you need:

Since there is no widget in the title of the page in our topic and we can not just copy and paste the shortcode there, we will use the WordPress do_shortcode function. It looks like this:

<?php echo do_shortcode( ‘[your shortcode goes here]’ ); ?>

Now we will add the WpDevArt contact form to our footer, for adding the shortcode we need to edit the footer.php file. It is highly recommended to backup your WordPress site before making changes to the main WordPress files.

After the backup, you need to open your website hosting files or use Filezilla to edit the footer.php. Go to the WordPress installation directory (usually this is public_html) and go to the wp-content > Themes directory. Find the folder of your current theme and open it. As we are going to add the contact form to the footer, we open the footer.php file.

Scroll through the page and find the exact location where you want to add the form. Our shortcode with the do_shortcode function will look like this:

That’s all. It’s very simple, but again don’t forget to save file before you made any changes.

2 Comments

Leave a comment