By default, WordPress won’t let you run/execute any PHP script written in page or post or widgets. Still if you want to run from there, one of the easiest way is to create shortcode in theme functions.php file and calling that function in a Post/Page/Widgets.
There are different plugins available in the WordPress plugin repository which can help you do that. In this article, we will show you how to execute PHP script in Page/Post/Widgets. After you install and activate the plugin, it will allow you to enter the PHP code directly in Post/Page/Widgets. Once you publish or preview the page, the php code will be executed and you will see the output directly on that post or page.
- Navigate to Plugins -> Add New
- Search for ‘Insert PHP‘
- Install and Activate it
- Add new post/page or edit existing one
- Be sure to switch to Text Editor mode from Visual one to place shortcode
- Write you PHP code and replace <?php tag with [insert_php] and ?> with [/insert_php]
For Example:1234[insert_php]
echo 'Current year is:';
echo date('Y')
[/insert_php]
- Publish or preview your post/page to see the output
Now you can easily run any PHP code from posts and pages directly and all you have to do is to replace PHP tags with the shortcode. Still, be careful because the plugin can’t do magic – all coding errors will be executed as well. If you need more information about the plugin, please visit the official pages. If you want to run the PHP code from Text Widget, you can do that without the need for a plugin.