How to Execute PHP Code Directly in WordPress Posts, Pages and Widgets

hedgehog-mascot

Sometimes bloggers need to execute a specific snippet of PHP code in their WordPress posts, pages, or in a widget. For security reasons this is not possible in WordPress. To enable the execution of PHP code in such places, you have to install and activate a specialized plugin.

Let’s suppose that you are not big on programming and you simply want to add one little piece of PHP code to one of your posts. You found your code somewhere on the internet but when you add it to your post, it simply shows up as text.

Exec-PHP

My plugin of choice for this situation is Exec-PHP.

Install and activate the plugin.

Go to WordPress Dashboard > Settings > Exec-PHP and tick the checkbox called Execute PHP code in text widgets.

exec-php-settings

Exec-PHP Settings

Click on the Save Changes button.

Only users with the administrator role assigned will have the ability to execute PHP in posts, pages, or widgets on your WordPress site. In most cases this is only you because most blogs tend to have only one user — the admin.

Now go to WordPress Dashboard > Users > Your Profile.

exec-php-user-settings

Exec-PHP User Settings

Tick the checkbox called Disable WYSIWYG Conversion Warning and click on the Update Profile button.

Your plugin is set and now you (the admin of the site) are able to add PHP code wherever you wish.

Execute PHP Code

In a previous post I mentioned a line of PHP code that can reveal the ID of the current post or page.

That line of code is:

I added and executed the above line of code and the ID of the current post is immediately revealed:

Do Not Execute PHP Code

Now that you have the Exec-PHP plugin enabled, whenever you write a piece of PHP code on your website, it will get executed.

If you do not want the code to be executed, i.e. you only want to show it as text, you need to substitute the less than and greater than characters in your code.

Instead of this character <, you need to use &lt;.

And instead of this character >, you need to use &gt;.

Example

Do not write <?php the_ID(); ?> because it gets immediately executed and you will only see the output (1496) of the code and not the code itself.

Instead you need to write &lt;?php the_ID(); ?&gt;.

Liked this post?

Subscribe to our newsletter to receive early notification of new posts and deals:

Next Post »« Previous Post

Leave a Reply

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