How to allow PHP In WordPress text widget

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.

Leave a Comment