NB: Make sure you do a back up of your theme, files and database before attempting the tutorials

Easy

---- Last modified : Sep 10 2022

Estimated reading time : 0 minutes, 54 seconds - 104 words

With this tutorial, we will set up a function that will enable you to display PHP content in widgets. It is not a common practice, but it can come in handy. Our function runs the PHP inside the widget.

This is a widget_text filter.

//////////////////////// filter php pour widget WordPress HTML //////////////////////////////////////////////////////////////////////////// 
add_filter('widget_text','via_execute_php',100); 
function via_execute_php($html){ 
if(strpos($html,"<"."?php")!==false){ 
ob_start(); 
eval("?".">".$html); 
    $html=ob_get_contents(); ob_end_clean(); 
} 
return $html; 
}

The ob_start() triggers the process. As long as it’s executed, headers aside, nothing is sent to the browser, but it is temporarily cached.

The cached content can be copy/pasted with the ob_get_contents() function. In order to display the content, use the ob_end_flush() function where as ob_end_clean() will delete the content.

Learn more about the Widget Text filter

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>