Learn how to add a PHP page to WordPress step by step

How to Add a PHP Page to WordPress — 4 Methods with Code Examples (2026)

Adding a custom PHP page to WordPress is one of the most common tasks in WordPress development — and one where choosing the wrong method can introduce security vulnerabilities, break on theme updates, or create maintenance headaches that are disproportionate to the actual task.

This guide covers all four practical methods for running custom PHP inside WordPress pages, when to use each one, complete working code examples, and the security considerations developers often skip that can turn a simple custom page into a serious site vulnerability.

Why You Might Need a Custom PHP Page in WordPress

Custom PHP pages power a wide range of WordPress functionality that the standard editor cannot handle:

  • API integrations — fetching and displaying data from external services (Amazon, Google Maps, weather APIs, payment gateways)
  • Custom tools and calculators — building interactive tools like CTR calculators, quote generators, or mortgage calculators
  • Dynamic content — displaying database-driven content with custom queries outside the standard loop
  • Custom admin pages — building WordPress admin tools for clients or internal teams
  • Form processing — handling custom form submissions with server-side validation and database storage
  • Shortcode-powered widgets — creating reusable PHP components embeddable anywhere on the site

The right method depends on whether your page needs the WordPress theme wrapper (header, footer, navigation), whether it will be managed by non-developers through the admin, and whether it needs to be portable across theme updates.

Method 1 — Page Template (Recommended for Most Use Cases)

A WordPress page template is a PHP file in your theme folder that WordPress makes available as a selectable layout option when creating or editing a page. It is the cleanest, most maintainable method for custom PHP pages that need to inherit the site’s header, footer, and design.

Step 1 — Create the template file In your theme directory (/wp-content/themes/your-theme/), create a new PHP file. Name it descriptively based on its purpose — for example, template-quote-calculator.php.

Step 2 — Add the template header comment The comment block at the top of the file registers it as a named template in WordPress:

php

<?php

/*

 * Template Name: Quote Calculator

 * Template Post Type: page

 */

get_header();

?>

<main id=”main-content“>

    <div class=”container“>

        <h1><?php the_title(); ?></h1>

        <?php

        // Your custom PHP logic here

        $result = my_custom_calculation();

        echo ‘<p>Result: ‘ . esc_html( $result ) . ‘</p>’;

        ?>

    </div>

</main>

<?php get_footer(); ?>

Step 3 — Assign the template to a WordPress page Go to Pages → Add New in your WordPress admin. In the right sidebar under Page Attributes, select your template name (“Quote Calculator”) from the Template dropdown. Publish the page.

Your custom PHP now runs at the page’s URL, wrapped in your site’s full design.

When to use this method: Any custom page that should look like the rest of your site, be managed through the WordPress admin, and have a defined permalink. This is the correct approach for the vast majority of custom PHP page requirements.

Method 2 — Shortcode with Buffered Output

When you need to embed PHP logic inside an existing page or post — rather than creating a dedicated page — registering a shortcode is the correct approach.

Add this to your active theme’s functions.php or a custom plugin file:

php

<?php

function my_custom_tool_output() {

    ob_start();

    ?>

    <div class=”custom-tool“>

        <?php

        // Your custom PHP logic

        $value = sanitize_text_field( $_GET[‘input’] ?? );

        if ( $value ) {

            echo ‘<p>Processed: ‘ . esc_html( $value ) . ‘</p>’;

        }

        ?>

    </div>

    <?php

    return ob_get_clean();

}

add_shortcode( ‘my_tool’, ‘my_custom_tool_output’ );

Use [my_tool] in any WordPress post, page, or widget area.

Security note: Never use the eval() function inside shortcode callbacks and always sanitize any input variables using WordPress sanitization functions (sanitize_text_field(), absint(), sanitize_email()) before processing or displaying them.

When to use this method: Embedding a reusable PHP component (calculator, lookup tool, dynamic display) inside a standard WordPress page or post that otherwise contains normal content.

Method 3 — Slug-Based Page Template (WordPress Template Hierarchy)

WordPress automatically loads a theme file named page-{slug}.php for any page with a matching slug — with no template selection required in the admin. This is part of WordPress’s template hierarchy system.

If your page has the slug my-tool, create a file named page-my-tool.php in your theme directory. WordPress loads it automatically whenever that page URL is visited.

php

<?php

/* This file loads automatically for the page with slug: my-tool */

get_header();

?>

<section class=”tool-wrapper“>

    <h1>My Custom Tool</h1>

    <?php

    // Custom logic for this specific page

    ?>

</section>

<?php get_footer(); ?>

When to use this method: When you want automatic template assignment for a known, permanent page slug without adding template selection logic. Useful for client sites where you want guaranteed template loading without relying on admin configuration.

Method 4 — Standalone PHP File with WordPress Bootstrap

For specialized use cases — AJAX handlers, webhook endpoints, cron job endpoints, or pages that explicitly should not render the WordPress theme — a standalone PHP file that bootstraps WordPress without loading the full template stack is appropriate.

php

<?php

/**

 * Standalone WordPress endpoint

 * Place in: /wp-content/plugins/my-plugin/endpoints/webhook-handler.php

 */

// Bootstrap WordPress without template loading

define( ‘SHORTINIT’, true );

require_once dirname( __FILE__, 4 ) . ‘/wp-load.php’;

// Verify request method and authentication

if ( $_SERVER[‘REQUEST_METHOD’] !== ‘POST’ ) {

    wp_die( ‘Invalid request method’, 403 );

}

// Verify nonce or secret key for security

$secret = sanitize_text_field( $_POST[‘secret’] ?? );

if ( $secret !== get_option( ‘my_plugin_webhook_secret’ ) ) {

    wp_die( ‘Unauthorized’, 401 );

}

// Process the request

$data = json_decode( file_get_contents( ‘php://input’ ), true );

// Handle $data…

wp_send_json_success( [ ‘received’ => true ] );

Critical security requirements for this method:

  • Always use SHORTINIT instead of loading the full WordPress stack when you do not need it — this significantly reduces execution time and attack surface
  • Always verify the request method (GET vs POST) and authenticate the request before processing any data
  • Never expose this file type without authentication — an unprotected wp-load.php bootstrap is a common security vulnerability

When to use this method: Webhook receivers, REST API-like custom endpoints, background processing scripts, or any PHP execution point that should not render HTML output.

Which Method Should You Use?

Use CaseRecommended Method
Custom page with site designMethod 1 — Page Template
Embed PHP inside an existing pageMethod 2 — Shortcode
Auto-load for a known page slugMethod 3 — Slug Template
Webhook or API endpointMethod 4 — Standalone with Bootstrap
Admin-only toolsRegister as a WordPress admin page via add_menu_page()

 

Security Best Practices for All Methods

Escape all output — Use esc_html(), esc_attr(), esc_url(), and wp_kses() on every variable displayed in HTML. External API data is particularly important to escape.

Sanitize all input — Use sanitize_text_field(), absint(), sanitize_email(), and other WordPress sanitization functions on every $_GET, $_POST, and $_REQUEST variable before use.

Verify nonces on form submissions — Use wp_nonce_field() and wp_verify_nonce() on all custom form processing to prevent cross-site request forgery.

Never edit WordPress core files — Any customizations made directly to WordPress core files (wp-includes/, wp-admin/) will be overwritten on the next WordPress update.

Use a child theme — Place custom page templates in a child theme, not the parent theme directly. Parent theme updates overwrite all files including custom templates.

Frequently Asked Questions

What is the safest way to add PHP to a WordPress page?

The page template method (Method 1) is the safest and most maintainable approach. It places your code in a properly structured WordPress template file, keeps it within the theme’s scope, uses WordPress’s built-in header and footer functions, and is easy to manage through the WordPress admin.

Can I add PHP code directly in the WordPress editor?

No. The WordPress block editor and classic editor do not execute PHP code by default — they treat it as plain text. You need to use one of the four methods described above to run PHP on a WordPress page.

What is get_header() and get_footer() in WordPress?

get_header() and get_footer() are WordPress template functions that load the theme’s header.php and footer.php files respectively. Including them in a custom page template ensures your page displays with the full site navigation, header design, footer links, and any scripts or styles registered by the theme.

Is it safe to use wp-load.php in a standalone PHP file?

It can be, if implemented correctly. The key requirements are: use SHORTINIT to avoid loading the full WordPress stack unnecessarily, always authenticate the request before processing any data, and never expose the endpoint URL without proper security checks. The example in Method 4 above demonstrates the correct implementation pattern.

Can I use this approach to build a WordPress plugin?

Yes — in fact, for complex custom PHP functionality, building a simple WordPress plugin (a .php file in /wp-content/plugins/ with a plugin header comment) is often cleaner than putting extensive code in functions.php. Plugins are easier to activate and deactivate without affecting the theme, and they survive theme changes and child theme switches cleanly.

Where should I put custom PHP code — functions.php or a plugin?

For site-specific functionality tied to the design (custom template modifications, minor hook adjustments), functions.php in a child theme is appropriate. For functional tools, API integrations, shortcodes, or anything that should persist regardless of which theme is active, a custom plugin is the better practice.

Build Faster with Pre-Built WordPress Plugins

If your custom PHP page requirement is a common use case — visitor analytics, form management, data sync, API integrations — a purpose-built WordPress plugin will be faster and more maintainable than a custom-coded page.

Browse purpose-built WordPress plugins from WP Codex Plugins for analytics, form management, API integrations, and WooCommerce automation.

View All WP Codex Plugins →

Try Free WordPress Tools →

 

Leave a Reply

Your email address will not be published. Required fields are marked *