By default, WordPress won’t let you execute any PHP code written in posts or pages. If you want to do something from there, one of the easiest ways is creating a shortcode in your theme’s functions.php file and calling that function in a post/page. You can also create a separate template file but if that’s not working for you and you really want to run the code directly from a post/page, you can still do that.
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 use Insert PHP. After you install and activate the plugin, it will allow you to enter the PHP code directly in posts and pages. Once you publish or preview the page, the code will be executed and you should see the output directly on that post or page.
- Navigate to Plugins->Add New
- Search for “Insert PHP” plugin
- Install and Activate it
- Add new post/page or modify an existing one
- Be sure to switch to Text Editor because Visual one won’t work for you in this case
- Write your PHP code:
- Replace <?php tag with [insert_php] and ?> with [/insert_php]
- Publish or preview your post/page to see the output
[insert_php] echo Current date and time is: '; echo date('l, F j, Y \a\t G:i:s'); [/insert_php]
That’s all there is. 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.
This is just one simple trick that can help you with your WordPress blog on an everyday basis. If you want to learn more, check the WordPress basics, get access to more tutorials, and don’t forget to check our other resources that will help you to level up your webmaster skills.