Quick WordPress Tip: How to execute AND display PHP in posts and pages

Say you’ve got some PHP code that you need to run from within one of your Pages. For example, in my Portfolio page, I use the FlickrRSS plugin to pull in photos from my Flickr feed. While the easiest way to implement that would be to place the required PHP snippet in a template file, I wanted to be able to display Page content after the photos, so I needed a way to allow PHP code to run from within a Page.

That’s the first step, and it’s got an easy solution — just install the Exec-PHP plugin, and all PHP within Posts and Pages will run as you’d expect it to.

The second requirement I have for my blog is that, such as in this WordPress Tip, I want to display PHP code as part of a tutorial, within a <code> tag. Entering the PHP code as is will simply run it, which is no good. Perhaps you could replace the questions marks with ‘&#63;’ (the HTML code for the question mark character)? Elsewhere, that would be fine, but a <code> tag will display its contents exactly as you enter them, so you’d get that HTML code showing up.

The workaround I came up with is to install the Custom Fields Shortcodes plugin, which lets you display the contents of a Custom Field within a Page or a Post (I’ve gone into more detail in this post). Then you create a new custom field called, say, ‘PHP Example‘, and enter the code into it, replacing the question marks with the above HTML character.

<&#63;php echo "This is some PHP code" &#63;>

You can call this into your post with the [cf] plugin tag. So, in this example, you’d type:

<code>[cf]PHP Example[/cf]</code>

That will draw in the contents of the specified custom field, and show the code exactly as someone would need to enter it into their own code editor.

Comments on Quick WordPress Tip: How to execute AND display PHP in posts and pages

ohare airport limo service

Simple but very useful tips. That is great that you can share to others what you have done great.

Posted by ohare airport limo service (7 comments) on 15th April, 2010 at 10:44 am.

Leave a Comment





Rob Barrett Introduction