0

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.

1
  • 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. Commented Oct 31, 2013 at 5:56

2 Answers 2

2

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.

1
  • The combination TextWidget+Shortcode is quite powerful. Nice suggestion. Commented Oct 31, 2013 at 9:48
-1
function add_php_text($text) {
 if (strpos($text, '<' . '?') !== false) {
 ob_start();
 eval('?' . '>' . $text);
 $text = ob_get_contents();
 ob_end_clean();
 }
 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
  • -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. Commented Oct 31, 2013 at 6:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.