How can I add a PHP page to WordPress?

PhpWordpress

Php Problem Overview


I want to create a custom page for my WordPress blog that will execute my PHP code in it, whilst remaining a part of the overall site CSS/theme/design.

The PHP code will make use of third-party APIs (so I need to include other PHP files).

How do I accomplish this?

N.B.: I do not have a specific need to interact with the WordPress API - apart from including certain other PHP libraries, I need I have no other dependencies in the PHP code I want to include in a WordPress page. So obviously any solution that didn't require learning the WordPress API would be the best one.

Php Solutions


Solution 1 - Php

You don't need to interact with the API or use a plugin.

First, duplicate post.php or page.php in your theme folder (under /wp-content/themes/themename/).

Rename the new file as templatename.php (where templatename is what you want to call your new template). To add your new template to the list of available templates, enter the following at the top of the new file:

<?php
/*
Template Name: Name of Template
*/
?>

You can modify this file (using PHP) to include other files or whatever you need.

Then create a new page in your WordPress blog, and in the page editing screen you'll see a Template dropdown in the Attributes widget to the right. Select your new template and publish the page.

Your new page will use the PHP code defined in templatename.php

Source: Creating Custom Page Templates for Global Use

Solution 2 - Php

If you wanted to create your own .php file and interact with WordPress without 404 headers and keeping your current permalink structure there is no need for a template file for that one page.

I found that this approach works best, in your .php file:

<?php
    require_once(dirname(__FILE__) . '/wp-config.php');
    $wp->init();
    $wp->parse_request();
    $wp->query_posts();
    $wp->register_globals();
    $wp->send_headers();

    // Your WordPress functions here...
    echo site_url();
?>

Then you can simply perform any WordPress functions after this. Also, this assumes that your .php file is within the root of your WordPress site where your wp-config.php file is located.

This, to me, is a priceless discovery as I was using require_once(dirname(__FILE__) . '/wp-blog-header.php'); for the longest time as WordPress even tells you that this is the approach that you should use to integrate WordPress functions, except, it causes 404 headers, which is weird that they would want you to use this approach. Integrating WordPress with Your Website

I know many people have answered this question, and it already has an accepted answer, but here is a nice approach for a .php file within the root of your WordPress site (or technically anywhere you want in your site), that you can browse to and load without 404 headers!


Update: There is a way to use wp-blog-header.php without 404 headers, but this requires that you add in the headers manually. Something like this will work in the root of your WordPress installation:

<?php
    require_once(dirname(__FILE__) . '/wp-blog-header.php');
    header("HTTP/1.1 200 OK");
    header("Status: 200 All rosy");

    // Your WordPress functions here...
    echo site_url();
?>

Just to update you all on this, a little less code needed for this approach, but it's up to you on which one you use.

Solution 3 - Php

If you're like me, sometimes you want to be able to reference WordPress functions in a page which does not exist in the CMS. This way, it remains backend-specific and cannot be accidentally deleted by the client.

This is actually simple to do just by including the wp-blog-header.php file using a PHP require().

Here's an example that uses a query string to generate Facebook Open Graph (OG) data for any post.

Take the example of a link like http://example.com/yourfilename.php?1 where 1 is the ID of a post we want to generate OG data for:

Now in the contents of yourfilename.php which, for our convenience, is located in the root WordPress directory:

<?php
    require( dirname( __FILE__ ) . '/wp-blog-header.php' );

    $uri = $_SERVER['REQUEST_URI'];
    $pieces = explode("?", $uri);
    $post_id = intval( $pieces[1] );

    // og:title
    $title = get_the_title($post_id);

    // og:description
    $post = get_post($post_id);
    $descr = $post->post_excerpt;

    // og:image
    $img_data_array = get_attached_media('image', $post_id);
    $img_src = null;
    $img_count = 0;

    foreach ( $img_data_array as $img_data ) {
        if ( $img_count > 0 ) {
            break;
        } else {
            ++$img_count;
            $img_src = $img_data->guid;
        }
    } // end og:image

?>
<!DOCTYPE HTML>
<html>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=yes" />
<meta property="og:title" content="<?php echo $title; ?>" />
<meta property="og:description" content="<?php echo $descr; ?>" />
<meta property="og:locale" content="en_US" />
<meta property="og:type" content="website" />
<meta property="og:url" content="<?php echo site_url().'/your_redirect_path'.$post_id; ?>" />
<meta property="og:image" content="<?php echo $img_src; ?>" />
<meta property="og:site_name" content="Your Title" />
</html>

There you have it: generated sharing models for any post using the post's actual image, excerpt and title!

We could have created a special template and edited the permalink structure to do this, but since it's only needed for one page and because we don't want the client to delete it from within the CMS, this seemed like the cleaner option.


EDIT 2017: Please note that this approach is now deprecated

For WordPress installations from 2016+ please see https://stackoverflow.com/questions/2810124/how-can-i-add-a-php-page-to-wordpress/39800534#39800534 for extra parameters to include before outputting your page data to the browser.

Solution 4 - Php

Creating the template page is the correct answer. For this, just add this into the page you created inside the theme folder:

<?php
    /*
    Template Name: mytemplate
    */
?>

For running this code, you need to select "mytemplate" as the template of the page from the back end.

Please see this link for getting the correct details https://developer.wordpress.org/themes/template-files-section/page-template-files/.

Solution 5 - Php

Any answer did not cover if you need to add a PHP page outside of the WordPress Theme. This is the way.

You need to include wp-load.php.

<?php require_once('wp-load.php'); ?>

Then you can use any WordPress function on that page.

Solution 6 - Php

The best way to add PHP pages in WordPress to Page Template in the theme or child-theme folder.

How to create Page Template in WordPress.

Create a file named template-custom.php and put it in /wp-content/theme/my-theme/ .

<?php
 /*
 * Template Name: Custom Template
 * Custom template used for custom php code display
 * @package   Portafolio WordPress Theme
 * @author    Gufran Hasan
 * @copyright Copyright templatecustom.com
 * @link      http://www.templatecustom.com
 */
?>
<?php get_header(); ?>
<?php
  //write code here

 ?>

<?php get_footer(); ?>

For more details

Solution 7 - Php

> You can add any php file in under your active themes folder like > (/wp-content/themes/your_active_theme/) and then you can go to add new page from wp-admin and select this page template from page > template options.

<?php
/*
 Template Name: Your Template Name
 */
?>

> And there is one other way like you can include your file in > functions.php and create shortcode from that and then you can put that > shortcode in your page like this.

// CODE in functions.php 

function abc(){
 include_once('your_file_name.php');
}
add_shortcode('abc' , 'abc');

> And then you can use this shortcode in wp-admin side page like this > [abc].

Solution 8 - Php

You will want to take a look in to WordPress' plugin API.

This explains how to "hook" and "filter" in to different parts of the WordPress mechanics, so you can execute custom PHP code pretty much anywhere at any given time. This hooking, filtering, and custom code authoring can all take place in your functions.php file in any of your themes. Happy coding :)

Solution 9 - Php

If you don't want to deal with the WordPress API, then Adam's answer is really the best one.

If you were willing to deal with the API I would suggest hooking into the "template-redirect" hook, which would allow you to point a particular URL or page to an arbitrary PHP file while still having access to WordPress.

Solution 10 - Php

The widely accepted answer by Adam Hopkinson is not a fully automated method of creating a page! It requires a user to manually create a page in the back-end of WordPress (in the wp-admin dash). The problem with that is, a good plugin should have a fully automated setup. It should not require clients to manually create pages.

Also, some of the other widely accepted answers here involve creating a static page outside of WordPress, which then include only some of the WordPress functionality to achieve the themed header and footer. While that method may work in some cases, this can make integrating these pages with WordPress very difficult without having all its functionality included.

I think the best, fully automated, approach would be to create a page using wp_insert_post and have it reside in the database. An example and a great discussion about that, and how to prevent accidental deletion of the page by a user, can be found here: wordpress-automatically-creating-page

Frankly, I'm surprised this approach hasn't already been mentioned as an answer to this popular question (it has been posted for 7 years).

Solution 11 - Php

Create a page call it my-page.php and save it under your theme directory. Now, edit this php file and write the following line at the top of the page

<?php /* Template Name: My Page */ ?>

Write your PHP code under the custom page definition line, you can call your other WP template, functions inside this file.

Start like <?php require_once("header.php");?> OR

whatever way you are integrating your header and footer to keep the layout consistent.

Since this is a my page, you NEED TO CREATE A PAGE from WordPress admin panel. Go to Admin => Pages => Add New

Add a page title, depending upon how you have coded the custom page, you might add page body (description) as well. You can fully skip the description if it’s written in the custom php page.

At right hand side, select Template. Choose My Custom Page from the dropdown. You are all set! Go to the slug (permalink) created by [wordpress][1] and see the page.

Solution 12 - Php

Just create a page-mytitle.php file to the folder of the current theme, and from the Dashboard a page "mytitle".

Then when you invoke the page by the URL you are going to see the page-mytitle.php. You must add HTML, CSS, JavaScript, wp-loop, etc. to this PHP file (page-mytitle.php).

Solution 13 - Php

I know it's an old question but no one mentioned this way:
You can also create a file named page-my-custom-page.php in theme directory and publish a page with my-custom-page slug.
it is also possible to use wp functions to show page details (like the_content() to show that page contents).

now you can access that page using example.com/my-custom-page.

I'm not sure if it's an appropriate way, but tested and worked in WP 5.7.3

Solution 14 - Php

Apart from creating a custom template file and assigning that template to a page (like in the example in the accepted answer), there is also a way with the template naming convention that WordPress uses for loading templates (template hierarchy).

Create a new page and use the slug of that page for the template filename (create a template file named page-{slug}.php). WordPress will automatically load the template that fits to this rule.

Solution 15 - Php

Try this:

/**
 * The template for displaying demo page
 *
 * template name: demo template
 *
 */

Solution 16 - Php

As long as you store your php file in the wp-content folder, i. e. inside of a theme or a plugin, it only needs this to get full WP-Power inside the file:

$parse_uri = explode( 'wp-content', $_SERVER['SCRIPT_FILENAME'] );
require_once( $parse_uri[0] . 'wp-load.php' );

After that you can use the WP functions the usual way. I use this for example in my lyrics plugin to create a printable personalized PDF on the fly.

Solution 17 - Php

<?php /* Template Name: CustomPageT1 */ ?>

<?php get_header(); ?>

<div id="primary" class="content-area">
	<main id="main" class="site-main" role="main">
		<?php
		// Start the loop.
		while ( have_posts() ) : the_post();

			// Include the page content template.
			get_template_part( 'template-parts/content', 'page' );

			// If comments are open or we have at least one comment, load up the comment template.
			if ( comments_open() || get_comments_number() ) {
				comments_template();
			}

			// End of the loop.
		endwhile;
		?>

	</main><!-- .site-main -->

	<?php get_sidebar( 'content-bottom' ); ?>

</div><!-- .content-area -->

<?php get_sidebar(); ?>
<?php get_footer(); ?>

Solution 18 - Php

You can name your file "newpage.php" - put it in your theme directory in wp-content. You can make it a page template (see http://codex.wordpress.org/Pages...) or you can include it in one of the PHP files in your theme, such as header.php or single.php.

Even better, create a child theme and put it in there, so you leave your theme code alone, and it's easier to update.

http://codex.wordpress.org/Pages#Creating_Your_Own_Page_Templates

Solution 19 - Php

You can also directly use the PHP page, like to create the PHP page and run with full path.

Like, http://localhost/path/filename.php

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionblippyView Question on Stackoverflow
Solution 1 - PhpAdam HopkinsonView Answer on Stackoverflow
Solution 2 - PhpSolomon ClossonView Answer on Stackoverflow
Solution 3 - PhpDrewTView Answer on Stackoverflow
Solution 4 - Phpuser5742826View Answer on Stackoverflow
Solution 5 - PhpI am the Most Stupid PersonView Answer on Stackoverflow
Solution 6 - PhpGufran HasanView Answer on Stackoverflow
Solution 7 - PhpAjay KatariyaView Answer on Stackoverflow
Solution 8 - PhphsatterwhiteView Answer on Stackoverflow
Solution 9 - PhpStephen RView Answer on Stackoverflow
Solution 10 - PhpDamian GreenView Answer on Stackoverflow
Solution 11 - Phpashish thakorView Answer on Stackoverflow
Solution 12 - PhpElias KatsaniotisView Answer on Stackoverflow
Solution 13 - PhpMohammad SalehiView Answer on Stackoverflow
Solution 14 - PhpDanijelView Answer on Stackoverflow
Solution 15 - PhpHeena PatelView Answer on Stackoverflow
Solution 16 - PhpAndré R. KohlView Answer on Stackoverflow
Solution 17 - PhpAhmed ElcheikhView Answer on Stackoverflow
Solution 18 - PhpChandra KumarView Answer on Stackoverflow
Solution 19 - PhpnimView Answer on Stackoverflow