|

How to allow PHP in Posts/Pages/CPT in WordPress

PHP is server scripting language used by million of websites online. Even WordPress is created with PHP programming language. In WordPress, we use plugins to perform specific tasks and those plugins provide use shortcodes to include any PHP functionality inside WordPress site. But, what if there is no plugin available for the function you want to achieve using PHP?

That’s a big issue here, that’s why many of our readers asked, ‘how to allow PHP in posts/pages/cpt in WordPress’.

By default, WordPress doesn’t accept coding in its built in block editor, such as PHP, Javascript, etc besides HTML5 tags.

In this article you will find ways to execute PHP codes within posts, pages and custom post types in WordPress.

Allow PHP in Posts and Pages

All we need to do is to install and activate Insert PHP Code Snippet that will help you to be able to get access to use PHP just after installing and activating this plugin. 

Here is what you can do with this plugin:

  • Convert PHP snippets to shortcodes
  • Insert PHP code easily using shortcode
  • Support for PHP snippet shortcodes in widgets
  • Dropdown menu in TinyMCE editor to pick snippet shortcodes easily

Congrats! You have learnt, how to use PHP within posts, pages and CPTs in a WordPress site.

Alternatively Adding Custom Code to functions.php

If you prefer not to use a plugin, you can add custom code to your theme’s functions.php file or using code snippets plugin to execute PHP in content.

Related  How to: Play Videos in WordPress with Easy Video Player?

Steps:

  • Go to Appearance > Theme Editor in your WordPress dashboard
  • Select your theme’s functions.php file and paste the following function or use code snippets plugin
function execute_php($content) {
    if (strpos($content, '<?php') !== false) {
        ob_start();
        eval('?>' . $content);
        $content = ob_get_clean();
    }
    return $content;
}
add_filter('the_content', 'execute_php');
add_filter('widget_text', 'execute_php');

This code checks for PHP tags in your content and executes them.

Leave a Reply

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