I want to add a text widget to my new WordPress website, but in the text widget there are some PHP snippets and I am finding it difficult to do it.

Please help me Guys.

  • please provide more specific details on what you are trying to do. especially where are the snippets, what are they, and what are you trying to do. – Mark Kaplun Oct 31 '13 at 5:56

Instead you should consider using a shortcode. This is exactly the problem that shortcodes try to solve.

By default, Widgets don't process shortcodes, but that can be easily changed.

add_filter( 'widget_text', 'do_shortcode' );

This would allow you to use any shortcodes in the Widget text area. Next would be to get the PHP code you want to run in a shortcode.

This can be done with the add_shortcode() function. More details found here

add_shortcode( 'shortcode_tag', 'prefix_shortcode_tag' );
function prefix_shortcode_tag( $atts ) {
    extract( shortcode_atts( array(
      'foo' => 'no foo',
      'baz' => 'default baz'
    ), $atts ) );

    // your php code here

In the widget area, you can now use [shortcode_tag] and run the PHP code you want.

  • The combination TextWidget+Shortcode is quite powerful. Nice suggestion. – brasofilo Oct 31 '13 at 9:48
function add_php_text($text) {
 if (strpos($text, '<' . '?') !== false) {
 eval('?' . '>' . $text);
 $text = ob_get_contents();
 return $text;

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

Add this code to your functions.php and all the text widgets can use PHP code as long as it goes in the tags .

  • -1 because this will break anything that starts with <? even if it is not a proper php, it assumes that there is no text before or after the code. It might be good enough for very specific usage pattern but not as a general solution. – Mark Kaplun Oct 31 '13 at 6:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.