Shortcode Tutorial – do_shortcode() Function

Share this Article

WordPress shortcodes are square bracket strings ([ ]) that magically transform into something fascinating on the frontend.

WordPress shortcodes are in general meant for pages, posts, and widgets. But we have an easy way to insert shortcodes anywhere in our site. We will make use of wordpress function do_shortcode().

About do_shortcode(), it’s a wordpress function.

In the last tutorial we have seen that to use shortcode we need to past the shortcode into either page/post area. But by using this do_shortcode() wordpress function we can execute the shortcode function anywhere inside wordpress.

In the first value of this function we need to pass the shortcode_name which calls the callback function where you use it.

Let’s see in detail.

Syntax

do_shortcode( string $content, bool $ignore_html = false )

Parameter Details

$content

(string) (Required) Content to search for shortcodes.

$ignore_html

(bool) (Optional) When true, shortcodes inside HTML elements will be skipped.

Default value: false

<?php echo do_shortcode("[shortcode_name]"); ?>

Examples

Case #1: Let’s add shortcode to header.php

Open header.php file from your activated theme’s files.

<?php echo do_shortcode("[social_links]"); ?>

[social_links] this is the shortcode we have created in self-closed shortcode tutorial.

Inside header we will get the social links as,

Case #2: Let’s add shortcode to footer.php

Open footer.php file from your activated theme’s files

<?php echo do_shortcode('[h2_text]Sample content[/h2_text]'); ?>

<?php echo do_shortcode('[h2_text]Test content[/h2_text]'); ?>

Output

Successfully, we able to see this output. [h2_text] … [/h2_text] this is the shortcode we have created in enclosed shortcode tutorial.

Case #3: Enclosed Shortcode with Parameters inside footer.php

Inside footer.php file, needs to add this code

<?php echo do_shortcode('[h2_text fontsize="40px" color="#d33a2c"] Hi, Web Tutor [/h2_text]'); ?>

<?php echo do_shortcode('[h2_text fontsize="35px" color="#d99a2c"] Hi, Online Web Tutor [/h2_text]'); ?>

We learnt Enclosed shortcode with parameters in this tutorial.

Was this post helpful?

PHP Web Development Courses on Offer in just $4
PHP Web Development Courses on Offer in just $4