Get PHP and Shortcode to Work in WordPress Widgets

Getting PHP Working in Widgets

By default any PHP code won’t execute in WordPress widgets or sidebars, you can probably get by with a plugin but you can also add a function in your themes function.php file to allow PHP to run, what you need to declare is a custom function and filter.

//Allow PHP to run in Widgets
add_filter('widget_text','execute_php_widgets',10);

function execute_php_widgets($html){
   if(strpos($html,"<"."?php")!==false){
   ob_start();
   eval("?".">".$html);
   $html=ob_get_contents();
   ob_end_clean();
   }
return $html;
}

If you add the above in your theme or child theme – PHP is now enabled and will work in widget areas.

Getting ShortCode Working in Widgets

You also can’t get shortcode to work in widget areas by default, however a filter can be added to the functions.php file to make that work

// Use shortcodes in text widgets.
add_filter('widget_text', 'do_shortcode');

 

Getting ShortCode Working in PHP Templates

You can get shortcode working in WordPress php templates like so:

// Use shortcode in a native PHP file
<?php echo do_shortcode('http:myvideo.com'); ?>

If the code is to be inserted inbetween HTML make sure you keep the PHP opening and closing tags as above.

2 Comments

  1. […] What I wanted to also show is how you can take one of these testimonial data rows and display it in a widget on the home page that just pulls the first, last or random row from the actual testimonial page. Here I will be adding PHP code in widgets so you’ll  need to ensure that you are allowing PHP to run in widgets. […]

  2. […] you need to add the social sharing icons to a widget or page you can add in a php […]

Leave a Comment





%d bloggers like this: