303

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
citronic
  • 9,868
  • 14
  • 51
  • 74
  • you can use those plugins : http://wordpress.org/extend/plugins/exec-php/ or http://wordpress.org/extend/plugins/php-code-widget/ Hope it will help! – Michaël May 11 '10 at 11:16

19 Answers19

451

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Adam Hopkinson
  • 28,281
  • 7
  • 65
  • 99
  • 26
    The template option wasn't available until I created the file with the comment in it. Then the template option appeared. Nice - I was going to use shortcodes but this is way easier. – Dave Hilditch Mar 22 '13 at 14:56
  • 1
    Is there any downside of using a plugin for publishing php ? – Suhail Gupta Jun 12 '14 at 17:28
  • @SuhailGupta a plugin can be deactivated - so your theme could be installed but missing the php page because the plugin is inactive. With a template, the php page is a part of the theme so is always active for that theme – Adam Hopkinson Jun 26 '14 at 08:58
  • is it possible to make http requests to the pages in this way? – ig343 Dec 24 '15 at 17:13
  • 2
    A page is a page, when the browser views it that is an http request - so yes. – Adam Hopkinson Dec 30 '15 at 22:23
  • 1
    Like @DaveHilditch said, the comment is important. It started working for me when I added the comment. – TheWalkingData May 18 '16 at 04:38
  • 1
    as Dave Hilditch has said. – ittgung Jun 13 '16 at 07:12
  • @AdamHopkinson Kindly look into this question also. http://stackoverflow.com/questions/42039833/how-to-create-a-page-template-which-takes-php-codes-in-wordpress?noredirect=1#comment71254431_42039833 Why the page is not looking properly.. looking so messy... –  Feb 05 '17 at 06:24
  • 1
    This 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). A fully automated approach is discussed here: https://stackoverflow.com/questions/1186026/wordpress-automatically-creating-page – Damian Green Aug 05 '17 at 17:07
  • 3
    @DamianGreen the question doesn't ask for a fully automated way, and in fact shows a preference for avoiding the WP API – Adam Hopkinson Nov 28 '17 at 09:29
  • @AdamHopkinson I created my custom PHP page using this template method. However the WordPress header and footer sections are being included in the page without me calling it. How do I stop them from being included? I want full control over the HTML contents without any WordPress stuff getting added automatically. – qroberts Aug 21 '18 at 15:54
  • 1
    @qroberts that's a different question! It's likely already been answered on Stack - do a search, and if you don't find the answer than ask it as a new question – Adam Hopkinson Aug 30 '18 at 09:29
  • 7
    This answer feels wrong because it is not re-using the existing theme elements, but copy-pasting them (paragraph 2). If the theme is provided by a third party then it may receive theme updates that will not cascade through to a custom template. Further it adds complexity to changing the look and feel of your site, changing theme requires a rebuild of the custom page. Would a plugin not be better for these two reasons? The way I read the question, the OP wishes to add additional functionality, not additional theme elements *"use of 3rd party APIs"* – Philip Couling Dec 05 '18 at 12:06
  • 1
    For clarification... the page.php file it is asking you to copy is in the directory of the theme you are currently using. In other words if you are using storefront the file would be wordpress/wp-content/themes/storefront/page.php – RonnBlack Oct 23 '19 at 03:10
44

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Solomon Closson
  • 6,111
  • 14
  • 73
  • 115
  • Hrmm this is an interesting problem. I've never experienced any 404 header with using `require( dirname( __FILE__ ) . '/wp-blog-header.php' );` and I would say it might have something to do with the server cofiguration where you are hosting WP. Or else maybe it's a bug introduced in certain release versions of WP. – DrewT Jun 01 '17 at 16:37
  • 1
    Yet 404 Headers occur, and even Wordpress multisite file in `wp-activate.php` has to disable 404 header by setting `$wp_query->is_404 = false` when activating new multisites using `require( dirname( __FILE__ ) . '/wp-blog-header.php' );` at the top of this page. – Solomon Closson Jun 01 '17 at 18:44
  • 2
    i don't understand how you can not recreate the problem. It's very simple to recreate. Just install Wordpress, than create a .php file, use the `wp-blog-header.php` approach as defined on https://codex.wordpress.org/Integrating_WordPress_with_Your_Website than see the 404 header in your browser inspector tools. – Solomon Closson Jun 03 '17 at 05:04
  • The 404 is directly on the Page itself without a wp_query. Than, even if you define a wp_query of some sort the page is still being rendered as a 404 page: http://imgur.com/a/MuW4u – Solomon Closson Jun 05 '17 at 05:04
  • 1
    Here's a webpage that documents this problem also, in case you missed it during your intensive research on this problem: https://cooltrainer.org/fixing-false-404-headers-on-external-pages-including-wp-blog-header-php/ – Solomon Closson Jun 05 '17 at 05:19
  • If you need to build php files that use an API that needs to be validated and checks headers, than this approach will work best everytime, regardless if you are in a multisite environment or not. Or how your theme is structured, or anything else. This approach never fails. – Solomon Closson Jul 26 '17 at 00:48
  • 1
    The header issue is an issue that happens in the latest versions of WordPress, which is exactly what I suggested in my initial comment. Careful using words like 'never fails'. :) – DrewT Aug 24 '17 at 21:44
  • 1
    This is a very improper approach to a problem. By going this route, you are creating a solution that will only work so long as WP doesn't change its bootstrap. You should be leveraging hooks available to accomplish (easily) what this is trying to do. – Lawrence Johnson Oct 05 '19 at 00:10
  • how to call this page then, from wordpress ? – bansal Apr 03 '20 at 09:40
  • You save the page with a .php extension, than you just browse to the page with the .php extension you gave it relative to the site url. Not sure if that answers your question or not, but that's how you load up the page in your browser. The php page would not be in the wordpress backend, it is hard-coded. That's the purpose of the OP's question. To add a PHP page using Wordpress core functions as I understood it. If you want to use a php page and interact with it in wordpress backend, than you want a Page Template instead. – Solomon Closson Apr 08 '20 at 01:57
15

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 How can I add a PHP page to WordPress? for extra parameters to include before outputting your page data to the browser.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
DrewT
  • 4,983
  • 2
  • 40
  • 53
10

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/.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
9

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.

  • This idea was very useful to me. However check out [this post](https://stackoverflow.com/questions/2091521/how-to-call-wordpress-functions-in-custom-php-script/25240153#25240153) about using `require_once('wp-load.php');` correctly – optimiertes Oct 06 '18 at 13:19
4

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].

Ajay Katariya
  • 439
  • 9
  • 22
3

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

Gufran Hasan
  • 8,910
  • 7
  • 38
  • 51
2

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 :)

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
hsatterwhite
  • 7,160
  • 5
  • 26
  • 29
  • I don't really want to interact with the Wordpress API itself though - my PHP code is completely independent of any WP shenanigans. But I do need to reference external php files. Are you sure the API is what I need to learn in this case? – citronic May 11 '10 at 12:32
  • It all depends on what you're trying to do. Using the API can help in some cases and others be completely non-essential. It's all dependent on what you're trying to achieve. You could go with @adam's suggestion and use page templates or you could keep all of your custom code in one basket and then hook/filter in to different parts of WordPress. I'd say all and all, choose what works for your best and what you feel comfortable with. All three of these answers will accomplish what you want in one form or another. – hsatterwhite May 11 '10 at 12:50
2

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).

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
1

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Stephen R
  • 3,512
  • 1
  • 28
  • 45
1

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).

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Damian Green
  • 633
  • 2
  • 8
  • 13
  • 1
    Immediately after I wrote the above answer, I realized that the intent of the user was to be able to include PHP in the content of the page, this approach does not obviously allow for that; PHP can only be used to generate the content, not be included in the content, thus the page would be saved statically rather than dynamically. However, you could give the page a dynamic appearance by re-creating the page and its content (by providing the page ID) each time it is called. Your plugin would handle when and how this occurs, perhaps by monitoring $_SERVER["REQUEST_URI"] – Damian Green Aug 05 '17 at 19:10
  • 2
    In your answer you talk about preventing accidental deletion by the user. How do you do that? – G-J Aug 24 '17 at 20:36
1

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.

Inder
  • 3,711
  • 9
  • 27
  • 42
1

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

Mohammad Salehi
  • 565
  • 1
  • 12
  • 33
0

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Danijel
  • 12,408
  • 5
  • 38
  • 54
0

Try this:

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

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.

Dharman
  • 30,962
  • 25
  • 85
  • 135
André R. Kohl
  • 345
  • 3
  • 14
-2
<?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(); ?>
Ahmed Elcheikh
  • 526
  • 4
  • 5
-4

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Chandra Kumar
  • 4,127
  • 1
  • 17
  • 25
  • The link is half-broken: It redirects two times and there isn't any sub section named *"Creating Your Own Page Templates"*. The closest may or may not be sub section *"[Page Templates](https://wordpress.org/support/article/pages/#page-templates)*". There is also the separate page (same name) *[Page Templates](https://developer.wordpress.org/themes/template-files-section/page-template-files/)* – Peter Mortensen Nov 24 '19 at 21:25
-5

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
nim
  • 509
  • 6
  • 16