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