Develop

Pass PHP Code Inside of a WordPress Widget [without plugins]

I don’t consider myself a “theme developer”. I’m not spending months developing a bulletproof theme, reselling it and then providing continuous support for hundreds of users on Theme Forrest. Rather, I build custom themes that are tailored (fig 1.0) to my clients specifically. That being said, I don’t always give them access to “everything”…but one area I find they nearly always ask to take control of is the footer.

Tailoring Websites

[fig 1.0]

More often than not, the footers in my themes involve some dynamic content…like the date, and one or more references to bloginfo();. Well, if you’ve ever tried to pass PHP in a WordPress widget, you know the results aren’t pretty.

Solution

Here is a simple way to turn the WordPress default text widget into a PHP enabled widget…and it’s NOT a plugin!

	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;
	}

Explanation

I originally found this code over at Emanuele Feronato’s blog, where he has written up a very detailed explanation of what this function is doing. So, for the sake of time I’m going to redirect you there if you want more information: Executing php inside a WordPress widget.

{ 7 Comments }

  1. I have tried it personally, this code is fully functional in widget section. But i want to use it in post and pages. Can you tell me, how to do it or email me the way to do it.

  2. Badass! Thanks so much. Going to Ajaxify my Woocommerce shopping cart and NEEDED THIS! Didn’t know I could do this.

    • Chris Perryman

      Glad to have ben able to help!

  3. Marshall

    This is great and its working on my project. Thank you

    • Chris Perryman

      You’re welcome, Marshall…glad to help!

{ Respond }

Leave a response