Using PHP Inside Content of WordPress Blogs

Using PHP inside of content on WordPress sites may not produce the expected results. As WordPress is built in PHP, you might think you could just start typing PHP code inside a post to pull some information from a database. Sorry to say, but it doesn’t work that way.

WordPress takes your blog content and runs it through some backend shenanigans to create the output that you see on the screen. WP expects to find other content in posts, like text and images, not code.

To run PHP code inside a blog post or Page, you’ll have to work a little differently than simply filling up the space in the text editor.

There are two ways (at least) of using PHP inside WP blogs to produce the desired output. The first way is to set up a WP template page that points to a pre-written PHP page that is identified in a Page. The second way is to use a plugin that facilitates PHP code execution inside content areas in WordPress. Both ways have their advantages and disadvantages.

Using WP Template Pages to Execute PHP Code

A template page is used to identify a pre-written PHP page. By saying “a pre-written PHP page” I mean a .php file that you’ve already written and which has been executed successfully by a server. A template file has at the top of it a PHP comment which identifies the template name followed by an include statement that identifies the .php file. WP template files must follow this format to be properly identified by the WordPress engine as a template file.

<?php
/*
Template Name: soccer-roster
*/
include (TEMPLATEPATH . ‘/soccer-roster.php’);
?>

The above snippet  is a complete template file which indicates the name of the template as “soccer-roster” and the path to the associated PHP file, soccer-roster.php. The template file is best saved with “template” in the file name. It must be located in the site’s theme folder.

After creating the template file and .php file, upload both to the theme folder. Create a blank Page. Do not put anything where you would normally write the content, but go ahead and give it a meaningful title. On the Add New Page page, look for the “Page Attributes” widget. Click the down-arrow to expand the list of templates and select your template. Using the example above, you would select the “soccer-roster” template. If the template is not stored in the theme folder, it will not appear in this drop-down list. Save the page and preview it. The PHP code, from soccer-roster.php, should be executed just as you would expect.

PROs

  • No interference from WP, code interpreted as stand-alone PHP.
  • Page renders as expected.

CONs

  • Can only be used with Pages, not posts or text widgets.
  • May have to wrestle with adapting PHP output into style of site.
  • CAUTION: Use a child-theme to safely save site-specific template files.

If your site relies heavily on plugins, using template pages may be the best method, see below. If it’s not a big deal to style the PHP output pages like the rest of your site, creating WP Pages that use templates is a breeze. If you need to put code in a post or text widget, keep reading.

Using WP Plugins to Execute PHP Code

Modifying WordPress themes is not for everyone, so using a plugin to execute PHP code may be the easier option. There are more than a handful of plugins available for the task. I chose to use Exec-PHP plugin for WordPress. It is a very well documented plugin. Thank you, Sören.

Download, unpack, upload and activate the plugin in the usual fashion. Verify these settings to make the plugin do its magic:

  • Disable tag balancing by unchecking ‘WordPress should correct invalidly nested XHTML automatically’ in the Settings/Write menu.
  • Disable the WYSIWYG editor (visual editor) in the user’s settings through the Users/Your Profile menu.
  • Assign the ‘unfiltered_html’ capability to the user, if user is not the administrator. Can use role manager plugin to assign this capability to other users.
  • Assign the ‘exec_php’ capability to the user, if user is not the administrator. Can use role manager plugin to assign this capability to other users.

Once I disabled the visual editor, my site was ready to go.

PROs

  • Easy, just change a couple of settings in blog admin. Plugin gives highly visible warning on Add New Post or Add New Page pages if the settings are not correct.
  • PHP code can be written in the normal fashion using the <?php ?> tags. It does not need to be marked up in any special way as it might with other plugins.
  • PHP can be used in text widgets and posts, as well as Pages.

CONs

  • Can’t use plugins that embellish or rely on the WYSIWYG editor.

Didn’t try any other PHP-execution plugins because Exec-PHP worked as soon as the visual editor was disabled.

As mentioned either method will get you there, it’s just a matter of style. If you need the visual editor to create your posts, use the template method. If you want to put PHP code in posts and text widgets, use the plugin method. Good luck!

17 thoughts on “Using PHP Inside Content of WordPress Blogs”

  1. Hi Axe, this is kishore again, I do have a blog(not the above site) which covers about mobiles and most of the people browse it on mobile, so is there any way to code php to detect the device of the user and detect whether it is a mobile device or pc and then to display google adsense ads like regular ads and mobile site ads.

    Doing so I can simple double my earnings over the night. So could you please help me?

  2. Hey Kishore,
    If your site is a WordPress site, you might try one of the mobile-ready plugins to assure that mobile users can see your site as you intend it to be seen.
    If not, check out SitePoint’s bookstore — http://www.sitepoint.com/books/mobile1/ (not an affiliate link)
    They cover everything you need to know – it’s a big subject.
    For the next month you might be able to pick up some real gems at a cut rate during their holiday sale —
    http://www.sitepoint.com/sale/
    Good luck!

  3. Thanks so much for this!
    As a WP beginner, Using Template Pages to Execute PHP Code definitely works for me.
    Just one oddity, which I’m trying to figure out: The page displayed has the PHP output but not the blog’s frame (header, sidebar, footer).
    If I add the get_header() + + include sidebar + get_footer() around it, I get the whole frame, but the sidebar widgets (archives, categories) are empty.
    Surely there’s an easy way to fix this?
    Thanks!

  4. HI!
    Widgets continue to appear normal with full lists on all pages and posts, including a test page I’ve created after the new template page. In the new template page the categories widget shows “No categories”. Last comments, Archive and Pages are just empty although the titles are there. Hope that’s clearer…
    It just doesn’t seem the right thing to add get_header(), include sidebar, get_footer() etc on the PHP page or template page themselves (both options show, but with empty widgets)

  5. Template pages need to have the framework of the page included, so the calls to bring in the header, sidebar and footer make sense to me. I’m wondering if the widgets are empty due to some path issue? Are you using a child theme for your template pages?

    How are you adding your sidebars, the new or old way? WP codex customizing sidebars

  6. Pingback: Test | three60
  7. I think the best way to integrate PHP code inside a WordPress page or article is to develop a custom shortcode. WordPress will replace the shortcode found in the editor by the string returned by the callback function attached to that shortcode. This function can simply return a static string. It can also do a lot of computing, including database queries.

    I’ve written an article on the subject : http://christianelagace.com/wordpress/les-shortcodes-wordpress/. It is in french but you will see the major facts you should know to develop your own shortcodes.

    Good luck !

     

  8. Hey Christiane!

    Thanks for your input. I think you’ve got it right. Allowing WordPress to return a value or string will allow for database shenanigans to occur behind the scenes and not right in a post or comment. I’ve checked out your article and will return to digest it more completely.

    Thanks again for pointing us to the right path.

Leave a Reply

Your email address will not be published.