How to call a WordPress shortcode within a template?

At a glance

Reading time

~200 words/min

Published

6 years ago

Mar 6, 2020

Views

4.2K

All-time total

Status

Archived

Outdated

This post is archived. Content may be outdated compared to newer versions.

How to call a WordPress shortcode within a template?

Shortcodes are used to add more functionality and features to your WordPress site. It’s a way of writing clean code at the backend and reusing it wherever you want. This article will help you to place the shortcode at the template using the following syntax.

syntax do_shortcode( string $content, bool $ignore_html = false )
 
  1. Define the ShortCode

Create the shortcut with the relevant functionalities and place it in the Theme functions file (functions.php) as shown below

 
function sample_shorty(){
	return 'Hello World!';
}

add_shortcode('sample_short_code', 'sample_shorty');
 
  1. Placing in the Template

After, creating the shortcode in functions.php place the shortcode in any template file in the theme folder as shown below.

<?php echo do_shortcode("[sample_short_code]"); ?>
 
  1. Placing in Pages

Guttenberg comes with a shortcode widget to place your functionalities anywhere within the page.

 

shortcode widget

  1. Passing Parameters to Shortcode

Shortcodes allow us to pass parameters to extend the functionality of the given function. The parameters are passed in an array of attributes.

Define the shortcode functions in the functions.php file as below.

function sample_parameter($atts){
   $atts = array_change_key_case((array)$atts, CASE_LOWER);
   return print_r($attr);
}

add_shortcode('sample_para_shortcode', 'sample_parameter');
 

When you’re accessing the shortcode, pass the parameter to extend the functionality as shown below.

[sample_para_shortcode="1"]
 

and it can be used in the template as below,

<?php echo do_shortcode("[sample_para_shortcode='1']"); ?>
 
Share

Related posts

How to install WordPress with Nginx on Ubuntu 18.04

In this tutorial you’ll learn to set up WordPress the most popular CMS (content management system) on ubuntu 18.04.

6 years ago