Question:

Correct code to use php in text widget

Victoria: 5 days ago

This code is used to display php inside a text widget

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

I'm currently using it in my theme. I'm constantly looking for better ways to do things. Every google search and website returned tells you to use this code or code similiar to this. With one google search I came up with this question How to allow PHP In WordPress text widget (https://wordpress.stackexchange.com/questions/120734/how-to-allow-php-in-wordpress-text-widget). One user came up with code similiar to this to which @Mark Kaplun commented that it will break anything that starts with <?

My question now is, I like to use the text widget to quickly test code like say something like related posts before coding it into my theme. Creating a shortcode here is unneccesary. Is there a better way to allow php in a text widget.

Answer:
Audrey: 5 days ago

I think this is enough, inside the widget-function of your Widget-class.

ob_start();
eval( '?>' . $html );
$html = ob_get_contents();
ob_end_clean();

Alternative use a maintenant plugin for this job, like PHP Code Widget (http://wordpress.org/plugins/php-code-widget/)