How to run PHP code directly from WordPress posts and pages

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.

    1. Navigate to Plugins->Add New
    2. Search for “Insert PHP” plugin
    3. Install and Activate it
    4. Add new post/page or modify an existing one
    5. Be sure to switch to Text Editor because Visual one won’t work for you in this case
    6. Write your PHP code:
    7. For example:

    8. Replace <?php tag with [insert_php] and ?> with [/insert_php]
    9. For example:

      [insert_php]
      echo Current date and time is: ';
      
      echo date('l, F j, Y \a\t G:i:s');
      
      [/insert_php]
    10. Publish or preview your post/page to see the output


    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.

START YOUR OWN BLOG

This guide is an introduction to mastering the art of blogging. It provides easy to follow steps to start, maintain, and grow your blog.

Read the guide

Leave a Reply

Your email address will not be published. Required fields are marked *