Add php to the text widget

Posted on 11th September, 2013 Leave a Comment

This is a real beaut of a snippet and deservedly belongs a place in the “Must Have Snippets” hall of fame.

Basically all this does it allow you to add and then process php inside the text widget, which means that you won’t need to use a plugin!

Add this to your functions.php:

/**
 * Allow the use of PHP in the 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;
}

Then when you add your text widget you’ll be able to do things like this!

<img src="<?php bloginfo('template_directory'); ?>/images/image-source.php" alt="loading images straight from " />

Original post found at www.emanueleferonato.com

Leave a Comment

To preserve code added to a comment you can wrap your code in short tags
by using [square brackets]:

  1. PHP use - [php] <?php code here ?> [/php]
  2. CSS use - [css] #code-here {} [/css]
  3. HTML use - [html] <div> code here </div> [/html]
  4. JS use - [js] $(".codeHere") [/js]