How to Insert PHP Code in WordPress Post, Page and Widget Area
Many times we need to insert custom PHP code in WordPress Posts, pages, and widget areas, in this post we will know “Insert PHP code snippet”. There are a few ways to outcome from this.
First, we can use a plugin to do it, which is the easiest and safer option. If we go with a plugin solution, then there are many plugins are available. In all these plugins, we go with “PHP Code Snippet”.
ADDING PHP TO YOUR POST WITH PLUGIN:
Install The Plugin Manually
- To download plugin go to WordPress.org’s Plugin page.
- After download go to WordPress Admin Panel -> Plugins -> Add New -> Upload Plugin [top left].
- To select file click “Browse” or “choose file” -> select the Plugin file from your system -> click “Install Now”.
- After Installation, click on “activate plugin’ to activate it.
Install The Plugin Automatically
- Login with your WordPress Admin Panel -> Plugins -> Add New.
- In the search area search for “PHP Code Snippet” and click Enter.
- In the search results choose the plugin “PHP Code Snippet” and click “Install Now”.
- After installation, to activate the plugin click on “Activate Plugin”.
List of Plugin to Execute PHP code
In this post we will use “PHP Code Snippet” plugin to “Insert PHP code snippet”.
Download “PHP Code Snippet” plugin, after install make it active.
Then navigate “PHP Code Snippet” section in “Plugin’s” menu and click on “Add New PHP Code Snippet“.
In this panel you can make your own snippet.
Simply add PHP code in snippet text box, then click create.
It will active by default, for sure by mouse over the icon on the left side of the “actions” column.
To add snippet in your post or page:
If you are using “Block” editor, first add classic block in your post.
In this editor, there is an icon of PHP to fetch Snippet.
After selecting any snippet the code will be like this and your code will show on your page or post:
Adding the PHP snippet your post manually:
Of course, you can just copy paste the shortcode of your snippet anywhere in your post and pages using the format below.
[xyz-ips snippet=”Demo-Snippet”]
ADDING PHP TO YOUR POST WITH A SHORTCODE
If you don’t want to use another plugin with your theme, you can do this manually with the same result. To use this method you must work with a child theme. Because the theme gets updated in that case your code will not be overwritten. Using this method first find out “functions.php” file in the theme directory and add your shortcode.
function demoFunc($varname){ return "Hello PHP!" ; } add_shortcode( 'demo', 'demoFunc' );
Save the function, now you can call it in your post or page with [demo].