Build 10 games and learn game development along the way in this fast paced game development course

Get the source code of 12 commercial games, loaded 50+ million times, and learn the secrets of game design

Learn how to make a successful Flash game from a real world example. Fully commented source code

Create realistic Flash physics games from scratch with advanced features, from Angry Birds to Crush the Castle

Executing php inside a WordPress widget without any plugin

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.

Rate this post: 1 Star2 Stars3 Stars4 Stars5 Stars (39 votes, average: 4.72 out of 5)
Loading...Loading...
Learn how to make a successful commercial Flash game from a real world example: get the fully commented source code of Globez, a Flash game played millions of times which generated a four figure income. Limited copies available.

Get it now
Be my fan on Facebook and follow me on Twitter! Exclusive content for my Facebook fans and Twitter followers

This post has 71 comments

  1. Monit

    on April 11, 2011 at 11:54 am

    Awesome :) It will surely save a lot of time thanks for the cool tip

    Monit

  2. fano

    on June 15, 2011 at 7:19 pm

    Saved me a lot of time.
    Thanks a bunch!

  3. Renji

    on September 4, 2011 at 10:29 pm

    Thanks for this Emanuele.

  4. eric erickson

    on September 12, 2011 at 12:24 pm

    THANKS! Awesome little piece of coding – saved me a LOT of headaches!

  5. Execute PHP in Wordpress text widget | Lizardwebs Clayton Computer Services

    on September 15, 2011 at 4:18 pm

    […] The prior code I was using here wasn’t cutting it for some reason – thanks to Emanuele Feronato for this awesome chunk of […]

  6. xhtmlpress

    on November 6, 2011 at 8:38 am

    I also wanted to run some custom code inside the widget but I programmed it in different way. I think this is very clean and simple approach. Thank you for your effort

  7. Arif

    on November 30, 2011 at 6:42 am

    Thank you so much. I really wanted exactly like this.

  8. krembo99

    on December 27, 2011 at 7:31 am

    This is great !!
    However , somehow after adding this code to functions.php – I can only add 1 text widget !

  9. estesparkinformation

    on January 1, 2012 at 12:07 am

    Wow, thanks so much for posting this. I didn’t want to install yet another plugin and slow my site down. This worked perfectly! Thank you!

  10. kiran

    on January 23, 2012 at 9:03 am

    Hi,
    i wont to execute php code in the post section how to do that plz help me

  11. Richard

    on January 23, 2012 at 10:52 am

    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?

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

    on February 29, 2012 at 3:58 pm

    […] nas?l çal??t??? hakk?nda detayl? aç?klama ve örnek için, yaz?n?n kayna?? olan bu linke […]

  13. Ionut

    on March 5, 2012 at 1:03 pm

    Anche a me piace Coca-Cola ;) … ! Thank you for explanations too :)

  14. akhatam

    on March 29, 2012 at 7:48 pm

    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

  15. Genuineapps

    on April 11, 2012 at 1:31 pm

    thank you brother……. i need to add code inside post not in widget plz tel me how to do that

  16. CoursesWeb

    on April 14, 2012 at 10:30 am

    Hi,
    I just wanna express my opinion that is a great tutorial if it really works.

  17. Aman

    on April 26, 2012 at 8:49 pm

    Hi,

    How can i do it with post and pages content area

  18. Bharat Chowdary

    on May 5, 2012 at 11:01 am

    Cant wait to try this on my blog, awesome stuff :)

  19. How to Execute php in WordPress Text Widget without a Plugin

    on May 10, 2012 at 12:01 pm

    […] More information on this code snippet is available at Emanuele Feronato. […]

  20. Raj

    on May 10, 2012 at 4:20 pm

    Killer code, this is one awesome and works pretty well..

  21. Lee

    on May 22, 2012 at 6:04 pm

    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!

  22. Henry

    on June 15, 2012 at 2:57 pm

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

  23. Desk Coder

    on June 16, 2012 at 6:50 pm

    Awesome. I am always skeptical of plug-ins, since I think they add more overhead than needed. This works great!

  24. igor

    on June 25, 2012 at 6:05 pm

    how can I enable the php in post also????

  25. Taylor

    on August 17, 2012 at 12:18 am

    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.

  26. 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

    on September 6, 2012 at 9:11 am

    […] “ausgespuckt”.Das war’s…ohne Plugin, ohne Wartungsaufwand. Vielen Dank an Emanuele Feronato. Gino Cremer (56 Beiträge)Ich bin Grafiker und Webdesigner aus dem Belgischen Eupen mit […]

  27. Widgets Gone Wild - How to Extend Widgets WIthout a Plugin

    on October 9, 2012 at 8:48 pm

    […] Done? Now you can pop PHP into a sidebar widget and it’ll work like a charm! If you’d like to know why the code works, I invite you to read this explanation by Emanuele Feronato. […]

  28. Como ejecutar código PHP en un widget de wordpress - Redes Sociales

    on October 15, 2012 at 5:27 pm

    […] Artículo traducido del inglés de este enlace. […]

  29. How to Execute PHP in WordPress Text Widgets without any Plugins

    on November 7, 2012 at 12:12 pm

    […] explanation on how this function works is available here. This function is pretty handy as you do not have to increase the server load by installing another […]

  30. Exécuter du code PHP dans WordPress sans installer d'extensions

    on November 7, 2012 at 4:24 pm

    […] détaillée de la façon dont cette fonction est disponible ici . Cette fonction est très pratique car vous n’aurez pas besoin d’installer des […]

  31. External Story List - Page 2

    on November 17, 2012 at 7:41 am

    […] for WordPress sites, follow the procedure explained here: Executing php inside a WordPress widget without any plugin – Emanuele Feronato. It works just fine! 0 Reply With […]

  32. venkateswar

    on November 23, 2012 at 9:20 am

    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)

  33. Vince

    on December 4, 2012 at 11:33 am

    That’s great, thanks

  34. Nurlan

    on December 5, 2012 at 12:01 pm

    why antivirus has shown on eval, ob_get_content that this virus?

  35. gaurav

    on January 11, 2013 at 9:12 am

    thanks for the post …you saved my day

  36. Backlink Butler

    on February 6, 2013 at 11:36 am

    very good code, thanks a lot fom germany!

  37. Dev

    on February 7, 2013 at 12:12 pm

    Thank you so much!

  38. Rita

    on February 16, 2013 at 5:06 am

    This works beautifully — so nice to add just a tiny bit of code rather than search through plugins. Thank you!!!!

  39. StereoLaunch

    on February 19, 2013 at 5:58 am

    Thanks so much for this! Quick, easy and worked perfectly! Saved me a lot of time!

  40. ElMuchacho

    on February 21, 2013 at 1:28 pm

    Proper handy! I hate adding unnecessary plugins.

    Thanks!

    Good Day Sunshine!

  41. How to Excecute PHP code in WordPress Text Widget - WPSnippy

    on April 21, 2013 at 2:36 am

    […] Filter Reference, widget_text, Source code Share this:More Pin ItDiggShare on […]

  42. PHP code on Wordpress Widget area without plugin

    on April 29, 2013 at 9:37 am

    […] more on here VN:F [1.9.22_1171]please wait…Rating: 10.0/10 (1 vote cast)VN:F [1.9.22_1171]Rating: 0 (from 0 […]

  43. How to execute PHP code in Text Widget without using Plugin

    on May 5, 2013 at 8:13 pm

    […] should see “Hello World !!!”If you want to understand the code then visit – Emanuele Feronato – italian geek and PROgrammervia – WPSquarevar dd_offset_from_content=40;var […]

  44. Roger Sanchez

    on May 6, 2013 at 11:17 pm

    Awesome!…Just what I was looking for: it’s always a treat to not use plugins and this one did exactly what I needed it to – you are the MAN :)!

  45. Giorgio Riccardi

    on June 2, 2013 at 8:02 pm

    Cool! that’s very handy.
    Thanks for all your efforts ;-)

  46. Como ejecutar código PHP en un widget de wordpress - Redes SocialesTuNegocioEnLaNube

    on June 19, 2013 at 12:52 am

    […] Artículo traducido del inglés de este enlace. […]

  47. Antonio

    on July 10, 2013 at 1:49 pm

    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…

  48. modf1x

    on July 12, 2013 at 12:55 pm

    thnx ;)

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

    on July 26, 2013 at 12:41 am

    […] Executing php inside a WordPress widget without any plugin by Emanuele Feronato (http://www.emanueleferonato.com) […]

  50. Zdenek

    on August 6, 2013 at 1:43 pm

    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 :)

  51. WordPress How To - Add a Shortlink for Twitter Users to Your Posts

    on September 29, 2013 at 2:12 pm

    […] above snip­pet is taken from Emanuele Feronato’s blog. If you want to know what the above snip­pet does, please check out his […]

  52. Ejecutar PHP en widgets de texto | Ayuda WordPress

    on October 7, 2013 at 12:09 am

    […] Esta opción es realmente sencilla, pues solo tienes que añadir al archivo functions.php de tu tema activo o a tu plugin de funciones el siguiente código: […]

  53. Ali

    on October 11, 2013 at 7:17 am

    Thanks a lot for this useful and brief solution.

  54. Tanaji

    on October 21, 2013 at 8:55 am

    Thanks a lot, It helps me and save my time

  55. WIDGET ? TEXT???? PHP ??? ?? ???? ?? - ??? 1??? ????

    on December 4, 2013 at 9:03 pm

    […] http://www.emanueleferonato.com/2011/04/11/executing-php-inside-a-wordpress-widget-without-any-plugi… […]

  56. orangorangan

    on February 25, 2014 at 9:13 am

    Great steps! now i can take down one plugin, thanks mate!

  57. Steve

    on March 1, 2014 at 3:17 pm

    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.

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

    on March 5, 2014 at 11:54 am

    […] Das war’s…ohne Plugin, ohne Wartungsaufwand. Vielen Dank an Emanuele Feronato. […]

  59. Patrick

    on March 13, 2014 at 8:25 pm

    Thank you!

  60. Shortcodes en PHP in Widgets - Dannybood.nl

    on March 24, 2014 at 12:05 am

    […] Meer informatie vind je hier. […]

  61. Paul Ratcliffe

    on April 23, 2014 at 12:45 pm

    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!

  62. Sergio Pinna

    on May 23, 2014 at 11:58 am

    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?

  63. Executing php inside a WordPress widget without any plugin – Emanuele Feronato | FauxPleather

    on July 27, 2014 at 8:16 pm

    […] via Executing php inside a WordPress widget without any plugin – Emanuele Feronato. […]

  64. Jan Anne

    on August 3, 2014 at 7:43 pm

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

  65. Michael

    on August 12, 2014 at 5:43 am

    @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!

  66. Shijith

    on August 27, 2014 at 8:15 am

    Excellent.
    Thanks a bunch.

  67. How to Execute PHP in WordPress Text Widgets without any Plugins – GizGat

    on September 2, 2014 at 11:09 pm

    […] to make the content available online.Detailed explanation on how this function works is available here. This function is pretty handy as you do not have to increase the server load by installing another […]

  68. Executing php inside a WordPress widget without any plugin | Indain Comics Online

    on October 8, 2014 at 7:23 pm

    […] Executing php inside a WordPress widget without any plugin […]

  69. Widget do umieszczania kodu PHP w WordPressie

    on October 13, 2014 at 8:27 pm

    […] Aby widget Tekst wykonywa? poprawnie kod PHP nale?y dopisa? poni?szy kod do pliku functions.php znajduj?cego si? w katalogu naszego motywu. Oryginalny kod wraz  z opisem w j?zyku angielskim znajdziesz tutaj. […]

  70. How to Execute PHP in WordPress Text Widgets without any Plugins - Tech Gizmo

    on October 24, 2014 at 10:22 pm

    […] explanation on how this function works is available here. This function is pretty handy as you do not have to increase the server load by installing another […]

  71. Sneha

    on October 29, 2014 at 6:19 pm

    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.

Thank you for the download!!

I hope you will find it useful and make something interesting out of it

To keep up to date with the blog, why don't you like my Facebook page and follow me on Twitter?

Want to learn more? Don't miss this:

Learn how to make a successful commercial Flash game from a real world example: get the fully commented source code of Globez, a Flash game played millions of times which generated a four figure income. Limited copies available.

Get it now

×