Here’s a useful little function for enabling PHP in the standard WordPress text widget.
//enable php in 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; }
It’ll look for the ‘<?php’ opening tag and the ‘?>’ closing tag and treat everything in it as PHP, rather than HTML. This is a huge advantage when trying to add WordPress specific PHP to pages without resorting to modifying the templates. I originally came across it here.
Just add the code to your child theme’s functions.php. If you’re not using a child theme, why not? Get one here in seconds for free.
Be sure to subscribe for more helpful code drops, tutorials and resources.
For me it is not working inside the text-module of Divi. The shortcodes are not working as well in Divi modules. Any other solutions?
Good post SJ. However, I would recommend not to use php code in a widget or text editor. The best and safest way is to convert your function in a shortcode and then use that shortcode using WordPress shortcode API. It’s a standard one. However, nice post.
That’s always an option too 🙂
I’ve found that PHP snippets are not compatible with DIVI ShortCodes. If I need code-based logic to determine whether to show or hide DIVI modules or to format columns using “[one_half][/one_half]” shortcodes to fit in with other parts of the page, you can’t do that from PHP snippets.