Executing php inside a WordPress widget without any plugin

Emanuele Feronato Php, WordPress

Sometimes in your WordPress theme you need to execute custom php code in a widget, because you want to display different information according to the category you are in, or simply because you need to execute a php script into that widget.

There are a lot of plugins doing this task, adding a new type of widget generally called “php widget”, but rather than installing a plugin this simple job can be done simply adding in functions.php file of your theme these few lines:

Which will turn the default Text widget into a php enabled widget.

Adding this feature directly to functions.php allows you to create a theme with this built in feature without the need of an external plugin. This is very useful when you plan to distribute your theme.

Let’s see how does it work:

Line 1: add_filter hooks a function to a specific filter action.

Filters are the hooks that WordPress launches to modify text of various types before adding it to the database or sending it to the browser screen.

The first parameter is the name of the filter to hook (widget_text) while te second is the name of the function to be called when the filter is applied (execute_php). The third is the priority, and 100 should grant us a very low priority since lower numbers correspond with earlier execution, and the default value is 10.

widget_text is the filter applied to the widget text of the WordPress Text widget.

So in the end we are telling WordPress to run execute_php function when the content of the text widget is generated.

Line 2: exexute_php function. Note the argument, the HTML generated by the Text widget.

Line 3: looking for <?php substring inside the HTML. If we find this substring, it means there is php to be executed inside the widget.

If you wonder why I am looking for "<"."?php" rather than "<?php", it’s just to preserve the correct syntax highlighting in most editors.

Line 4: ob_start() turns output buffering on. While output buffering is active no output is sent from the script, instead the output is stored in an internal buffer. This means the HTML produced by the Text widget is temporarily saved into an internal buffer.

Line 5 : at this time we need to evaluate the HTML as if it was a php script. eval function does the job, but we need to add <> to the HTML (again, split in two to avoid highlight issues) because we must tell eval function the php could not start from the beginning of the HTML string.

An example: if my Text widget contains

everything will work fine because the Text starts with php. But in this case:

eval function will fail because everything before <?php is parsed as php, returning an error. That’s why the text is changed to

to tell eval we don’t start with php code.

Lines 6 and 7: once the php has been processed, we need to save the output buffer content, clean the output buffer and turn off output buffering.

Finally at line 9 the HTML is returned, with the php correctly parsed.

And that’s all, without needing any plugin.

Want to learn more? Learn by example!

Get the full commented source code of an actual commercial cross platform HTML5 game!!

Comments 71

  1. Pingback: Execute PHP in Wordpress text widget | Lizardwebs Clayton Computer Services

  2. Richard

    Good tutorial-thanks.
    I’m sure one day this will prove useful to know.

    I currently have a problem running a php script in a custom template WordPress page. The php breaks the theme structure-any tips on how I can fix?

  3. Pingback: Wordpress Widget içerisinde PHP kodlar?n? pluginsiz çal??t?rma | Ümit Y?ld?z

  4. akhatam

    Reallly nice.. but It is not work for me. Ive tried some php script to show recent post by category but nothing appear on my blog… how resolve it? or may you have the solution for me.. Thanks

  5. Pingback: How to Execute php in WordPress Text Widget without a Plugin

  6. Lee

    Just wanted to say thank you a thousand times.

    I was searching for hours to exclude one simple category from the categories widget, without a plugin.

    Another website gave me the hint to execute a code in the text widget, and this tutorial allowed me to do that.

    example of of a code:

    Thank you!

  7. Henry

    @Aman: Try this, it works for me (you have to filter ‘the_content’ as well.

    add_filter('the_content','execute_php',100);
    add_filter('widget_text','execute_php',100);
    function execute_php($html){
    if(strpos($html,"".$html);
    $html=ob_get_contents();
    ob_end_clean();
    }
    return $html;
    }

  8. Taylor

    I’m trying to add this code to enable a captcha on a php form on WordPress on the Contact Me form. Am I putting the code in the wrong place in the functions.php file? I thought I had done everything right. Now it still shows the php code commented out in the Chrome’s inspect element. It worked one time showing the whole captcha, but then I changed something and it got all fouled up.

  9. Pingback: Wordpress: PHP Code in statischem Text-Widget ausführen ohne Plugin - Apple,iPhone,iPad,Mac,iOS,Wordpress,Grafik,Webdesign: Tipps & Tricks...direkt aus der Pixelbar in Eupen! - Pixelbar Eupen - Pixelbar Eupen

  10. Pingback: Widgets Gone Wild - How to Extend Widgets WIthout a Plugin

  11. Pingback: Como ejecutar código PHP en un widget de wordpress - Redes Sociales

  12. Pingback: How to Execute PHP in WordPress Text Widgets without any Plugins

  13. Pingback: Exécuter du code PHP dans WordPress sans installer d'extensions

  14. Pingback: External Story List - Page 2

  15. venkateswar

    i have used the above code but getting this error

    Parse error: syntax error, unexpected ‘>’ in C:\xampp\htdocs\wordpress\wp-content\themes\made\functions.php(52)

  16. Pingback: How to Excecute PHP code in WordPress Text Widget - WPSnippy

  17. Pingback: PHP code on Wordpress Widget area without plugin

  18. Pingback: How to execute PHP code in Text Widget without using Plugin

  19. Pingback: Como ejecutar código PHP en un widget de wordpress - Redes SocialesTuNegocioEnLaNube

  20. Antonio

    I added the code in function.php but it doesn’t work.
    I tried to insert in post:

    In post page I don’t see anything, in html source I exactly see:

    I wonder why…

  21. Pingback: Useful Links: Execute php in a wordpress text widget | samchive.rs

  22. Zdenek

    Thanks for that. I was searching some kind of plugin to allow it and then Google showed me your page – much better (no plugin needed) and does exactly what I need. Thanks again :)

  23. Pingback: WordPress How To - Add a Shortlink for Twitter Users to Your Posts

  24. Pingback: Ejecutar PHP en widgets de texto | Ayuda WordPress

  25. Pingback: WIDGET ? TEXT???? PHP ??? ?? ???? ?? - ??? 1??? ????

  26. Steve

    That is a very handy little piece of code indeed. Thanks very much, there are many times I have looked for something similar but not found what I needed. This worked perfectly for me.

  27. Pingback: Wordpress: PHP Code in statischem Text-Widget ausführen ohne Plugin › Pixelbar GmbH Eupen - Webdesign since 2005

  28. Pingback: Shortcodes en PHP in Widgets - Dannybood.nl

  29. Paul Ratcliffe

    I can’t believe how many positive comments this article has got. Yes, it’s easy, but it’s an enormous security problem. You should never use eval() in this fashion – if you need custom PHP code then write it as a plugin, in functions.php or directly in the theme, not like this!

  30. Sergio Pinna

    Ciao Emanuele!

    Vorrei chiederti: e se volessi scrivere un testo misto HTML + PHP nel widget?

    Per esempio inserire come argomento del tag a un PHP? (o anche qualcosa di più complesso :-) )

    Posso utilizzare lo snippet da te prorposto?

  31. Pingback: Executing php inside a WordPress widget without any plugin – Emanuele Feronato | FauxPleather

  32. Jan Anne

    Thanks for sharing: very good explanation what the code does. Just 10 lines of codes and a plugin isn’t necessary anymore!

  33. Michael

    @Paul Ratcliffe
    Hey Paul,

    I was wondering the same thing.
    Would you be so kind to elaborate on the secure method you are suggesting as an alternative to Emanuele’s?

    Much appreciated!

  34. Pingback: How to Execute PHP in WordPress Text Widgets without any Plugins – GizGat

  35. Pingback: Executing php inside a WordPress widget without any plugin | Indain Comics Online

  36. Pingback: Widget do umieszczania kodu PHP w WordPressie

  37. Pingback: How to Execute PHP in WordPress Text Widgets without any Plugins - Tech Gizmo

  38. Sneha

    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.

Leave a Reply

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