PHP in WordPress

I’ve been using PHP in a lot of WordPress posts and pages recently. Usually I just make use of the Exec-PHP plugin. This allows you to put PHP in any page or post using the usual <?php opening and ?> closing tags.  It’s a little clunky for a few reasons, firstly if you edit the page or post in the WordPress Visual editor it messes up the code. You work-around that using the Disable Visual Editor WYSIWYG plugin. A second reason not to do it this way is that editing PHP in the WordPress is horrid. I’d much prefer editing in my IDE of choice where I get nice syntax highlighting and can format the code nicely.

However, there’s a big reason not to include complex PHP directly in your pages or posts. That’s because the PHP is included in the database record for the page or post. Never a great idea from a security point of view. It turns out if you have a need for a complex PHP driven page there’s an easier way. Take the case where we want to create a PHP driven page called “My PHP Page”.

  • In your child theme folder (you are using a child theme I hope) create a copy of your page.php file and call it page-my-php-page.php.
  • Create a new page in WordPress and call it “My PHP Page”.

Now when WordPress renders the new page called “My PHP Page” and it finds the page-my-php-page.php file in the theme directory it will use that file to generate the page content.

I have found this approach particularly useful if you are building a simple CRUD system in WordPress. I’ve created a series of files called (for example) page-add-record.php, page-delete-record.php, page-edit-record.php, page-view-records.php. Each file contains the code required to add/edit/delete/display the database records I am interested in. Then I just need to create corresponding pages in WordPress with the names “Add Record”, “Edit Record”, “Delete Record”, and “Display Records”.

This entry was posted in php, WordPress on by .

About markn

Mark is the owner and founder of Timesheets MTS Software, an mISV that develops and markets employee timesheet and time clock software. He's also a mechanical engineer, father of four, and a lifelong lover of gadgets.