Why do we need to Enable PHP Code in Text Widget

In certain cases, we need to execute the PHP code inside Text widget.

But if we just place the PHP code inside the widget, it will just show the code AS-IS in the page. By Default, whatever text that is typed in (other than HTML),same content will be shown in the page.

Enable PHP In Text Widget
Enable PHP In Text Widget

Though we can invoke the PHP code inside any template files, it will be handy if we are able to invoke PHP function from the Text Widget. Without the hurdle of going & find the right place, we can easily access the code and render the results using Text Widget.

Here is the Code to enable PHP execution

Add the below lines under Child Themes’ functions.php

function enable_php_code ($text) {
    if (strpos($text, '<' . '?') !== false) {
    ob_start();
    eval('?' . '>' . $text);
    $text = ob_get_contents();
    ob_end_clean();
    }
    return $text;
}
add_filter('widget_text', 'enable_php_code', 100);

 Code Explanation:

  • If a Text widget content contains the starting PHP tag ( <?), then the entire content till the end of PHP tag (?>) is understood and executed as PHP through eval function.
  • Results returned from the eval function is then returned and it is displayed in the place of Text Widget.
  • We need to mainly enable the filter to invoke our newly added function ( i.e., enable_php_code) whenever it encounters the Text Widget ( widget_text). Function add_filter() does this job.

Lets Test it by Displaying Today’s Date:

We will create a function to test this.

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:  Trying add this “displayDateFn();” line of code in your Text Widget (under Appearance -> Widgets) tags with php tags <?php and ?>.

Step 3: 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. Today’s date is returned from the function that we wrote and displayed.

We can easily enable PHP code in Text Widget by using this method and use it wherever required.

More Tricks: Display Thumbnails for Recent Posts without Plugin.

 

Leave a Reply