PHP Text Widget — Allow PHP In WordPress Text Widget

Have you ever wanted to use PHP in WordPress text widgets? All of us have. Here’s a neat little trick to allow you to insert PHP in WP text widgets. Sure, there are several plugins which allow you to do that. But isn’t it neat to use the default WordPress Text widget and give it the PHP dimension? Copy and paste this into your functions.php file and see the magic happen.


add_filter('widget_text', 'php_text', 99);

function php_text($text) {
 if (strpos($text, '<' . '?') !== false) {
 ob_start();
 eval('?' . '>' . $text);
 $text = ob_get_contents();
 ob_end_clean();
 }
 return $text;
}

Now all the text widgets can use PHP code as long as it goes in the <?php and ?> tags .

Source: PHP Text Widget

Posted In:

WordPress Support & Maintenance, Code Snippets

15 Comments

  1. Thanks for the tidbit of code. This did the trick for me.

    Reply
  2. I was very surprised to discover that this works like a charm!
    Thank you!

    Reply
  3. Was working on a wordpress site for a client, theme had shortcodes, I could mix the theme’s shortcodes and my additional php perfectly with your code, thanks !

    Reply
  4. Absolutely brilliant! God bless you, you’re a life saver!

    Reply
  5. Thank you!! I tried 4 popular plugins that were supposed to allow PHP in widgets, but none of them worked – the PHP code seemed to have no effect… but your code worked perfectly – so simple – thanks!

    Reply
  6. I was using PHP Code Widget but hell that didn’t work out. Tried out your little snippet, now cruising the luxury of php in widgets. Thanks Man!

    Reply
  7. This worked perfectly! I had tried someone else’s tutorial, but it didn’t work. thank you for helping improve my WordPress site.

    Reply
  8. Wow, thank you!

    Works like a charm for me too.

    Reply
  9. You are Ace, man… saved everyones life with your clean solution! KUTGW !

    Reply
  10. You, my friend, are a genius. I’m trying to get rid of extraneous plugins my useless theme developer stuffed into a custom theme. This worked perfectly for getting rid of the Advanced Text Widget plugin. Yea baby.

    Reply
  11. This worked perfectly! I had tried someone else’s tutorial, but it didn’t work. thank you for helping improve my WordPress site……

    Reply
  12. I was using PHP Code Widget but hell that didn’t work out. Tried out your little snippet, now cruising the luxury of php in widgets. Thanks Man!

    Reply

Comment on PHP Text Widget — Allow PHP In WordPress Text Widget

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