WordPress Snippets at WPcustoms

Execute PHP in text widgets

Add this function if you want to use php in a text widget. WordPress blocks php by default in widgets so this is a handy snippet to extend widgets usage. Please keep in mind that executing php on your site may lead to a security risk if you don’t know the user who is able to manage widgets. Malicious codes can be added.


/**
 * Snippet Name: Execute PHP in text widgets
 * Snippet URL: https://wpcustoms.net/snippets/execute-php-in-text-widgets/
 */
  function wpc_php_textwidget($text) {
 if (strpos($text, '<' . '?') !== false) {
 ob_start();
 eval('?' . '>' . $text);
 $text = ob_get_contents();
 ob_end_clean();
 }
 return $text;
}
add_filter('widget_text', 'wpc_php_textwidget', 99);