brock

Using PHP code in Posts & Pages

07 Sep 2008

There really is no other way around it: you need to be able to add php code to Posts & Pages if you are going to mod your WP install. I use so much PHP & custom SQL queries on the company intranet that WordPress is almost an aside to the main event.

But in order to use PHP code inside posts, pages & widgets, you need to get the Exec-PHP plugin. It is truly amazing. Once it is installed, just turn off your Rich Text Editor and start coding away. But what do you do when you want to display PHP code inside of one of your posts? There are times that you'll want to show off your PHP code without executing it. That can be done too. Taken from the exec-php homepage:
If you just want to print out code and don’t want to execute it, e.g. like it is done here on this page, you have to make sure to convert your code to the correct XHTML representation.

<

type

<

>

type

>

&

type

&

This is, however, very tedious if you think you'll put PHP in your code more than once. You can do this conversion much more intelligently by using the WP-Syntax plugin. It creates nice colorful code boxes and formats them to any code format (PHP, Java, HTML, C+, Ruby, etc). It looks like this:

<div id="navbar">
    <ul>
    <table width="100%">
        <tr>
            <td width="80%">
                <li><a href="<?php echo get_settings('home'); ?>">Home</a></li>
                <?php wp_list_pages('title_li=&depth=1&include=38'); ?>
                <li><a href="http://brockangelo.com/category/ubuntu/">Ubuntu</a></li>
                <li><a href="http://brockangelo.com/category/wordpress/">WordPress</a></li>
                <li><a href="<?php bloginfo('rss2_url'); ?>">RSS</a></li>
            </td>
            <td width="20%" align="right">
                <li><a><?php echo (date("g:i a")); ?></a></li>
            </td>
        </tr>
    </table>
    </ul>
</div>