Enable Shortcodes in Text Widget (WordPress)
Enable Shortcodes in Text Widget (WordPress)

Write your own PHP Code to Enable Shortcodes in Text Widget:

Text widgets are just wonderful feature available in WordPress. It is a multipurpose widget available and we can extend its usage according to our need.

Text widget can be used in many ways,

1)      Plain text can be displayed

2)      HTML code with div tags can be added

3)      Image can be loaded through text widget

4)      PHP functions can be invoked and returned results can be shown as output in the placement of text widget

5)      Shortcodes are another key feature of WordPress. Most of the plugins are providing complicated UI functionalities with a single line shortcodes. We can include these shortcodes in our PHP files. Apart from adding those shortcodes in the PHP files, we can also use them in Text Widget.

In the above mentioned points #4 and #5, we need to add minor code to our functions.php to make it work. In this post, lets see how to enable the Shortcodes in Text Widget.

Note: It is a good practice to make all required changes in your child theme’s functions.php and style.css. You can find out the creation of child themes explained in simple steps here.

Write your own PHP Code to Enable Shortcodes in Text Widget:

add_filter( 'widget_text', 'do_shortcode');

Yes, it is that simple. Locate your functions.php and add this line of code at the end just before the closing php tag.

Code Explanation:

This line invokes the do_shortcode function for all the text available under Text Widget. And if there are any shortcodes present in it, shortcode functionality would be executed and the results would be displayed to the user.

 Now it is Testing time – Create your own Shortcodes for Displaying Today’s Date:

If you are using any plugins that provides Shortcodes, you could try adding them in Text Widget and Test it. Here, we will create a simple shortcode to display Today’s Date and will test it after adding to Text Widget.

Step 1: Create a function to display Today’s Date under Child Themes’s functions.php.

function displayDateFn(){
  echo date_i18n('j F Y', time());
}

Step 2: Link & Assign the newly created function as a new Shortcode namely “printDate”.

add_shortcode("printDate", "displayDateFn");

Step 3: Yes, we are almost done with the creation of shortcode “printDate”. Trying add this below line of code in your Text Widget (under Appearance >> Widgets) tags.

[printDate]

Refresh the page after adding the Text widget to your sidebar and load your site. You could see Today’s date appearing in the sidebar. You can also test with any other shortcodes provided by plugins too.

Just one line of code helped to enable Shortcodes in Text Widget. Also, this article covered the creation of Shortcodes in simple steps.

Leave a Reply