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.
Here is the Code to enable PHP execution
Add the below lines under Child Themes' functions.phpfunction 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.