add custom php to WordPress pagesHave you ever wanted to insert your PHP code in a WordPress page? Well, in Joomla this is really straightforward and there are plenty of plugins such as Jumi and DirectPHP that can help you to achieve the goal. Using these plugins you can include PHP files or even directly embed your code inside an article. In contrast, I couldn’t find any alternative in WordPress and came up with a different solution: A Custom Page Template. This is a safe and easy way to add custom PHP to WordPress pages.

How to create a new page template

1. Follow the path to folder in which your WordPress theme is stored. In my case it’s:


You may find page templates files (starting with: template) that your theme uses by default.

2. Make a duplicate of an existing template file or page.php. You can rename it to keep the consistency with other page templates but it’s not necessary.

3. Open the file in a text editor and add the comment below at the top of it. You can replace “Custom page template” with your desired name:

4. Add your script wherever you want in the file. For example, I’ve added an script inside post content that generates a random number between 1 to 100 each time the page loads.

5. Create a new page and select the new template in Page Attributes.

Page Attributes

Page Attributes

6. Done! You can check the demo here.

Now it’s a good time to explore WordPress Developer Documentation to get the most out of this tutorial.