简体   繁体   English

如何将 PHP 页面添加到 WordPress?

[英]How can I add a PHP page to WordPress?

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.我想为我的 WordPress 博客创建一个自定义页面,它将在其中执行我的 PHP 代码,同时保留整个网站 CSS/主题/设计的一部分。

The PHP code will make use of third-party APIs (so I need to include other PHP files). PHP 代码将使用第三方 API(因此我需要包含其他 PHP 文件)。

How do I accomplish this?我该怎么做?

NB: 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.注意:我没有特定需要与 WordPress API 进行交互 - 除了包含某些其他 PHP 库之外,我需要在 WordPress 页面中包含的 PHP 代码中没有其他依赖项。 So obviously any solution that didn't require learning the WordPress API would be the best one.所以很明显,任何不需要学习 WordPress API 的解决方案都是最好的。

You don't need to interact with the API or use a plugin.您不需要与 API 交互或使用插件。

First, duplicate post.php or page.php in your theme folder (under /wp-content/themes/themename/ ).首先,在您的主题文件夹(在/wp-content/themes/themename/ )中复制post.phppage.php

Rename the new file as templatename.php (where templatename is what you want to call your new template).将新文件重命名为templatename.php (其中 templatename 是您要调用的新模板)。 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.您可以修改此文件(使用 PHP)以包含其他文件或任何您需要的文件。

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.然后在您的 WordPress 博客中创建一个新页面,在页面编辑屏幕中,您将在右侧的“属性”小部件中看到一个模板下拉列表。 Select your new template and publish the page.选择您的新模板并发布页面。

Your new page will use the PHP code defined in templatename.php您的新页面将使用templatename.php定义的 PHP 代码

Source: Creating Custom Page Templates for Global Use来源: 创建供全球使用的自定义页面模板

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.如果您想创建自己的 .php 文件并在没有 404 标头的情况下与 WordPress 交互并保持当前的永久链接结构,则不需要该页面的模板文件。

I found that this approach works best, in your .php file:我发现这种方法在您的 .php 文件中效果最好:

<?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.然后您可以在此之后简单地执行任何 WordPress 功能。 Also, this assumes that your .php file is within the root of your WordPress site where your wp-config.php file is located.此外,这假设您的 .php 文件位于您的wp-config.php文件所在的 WordPress 站点的根目录中。

This, to me, is a priceless discovery as I was using require_once(dirname(__FILE__) . '/wp-blog-header.php');对我来说,这是一个无价的发现,因为我正在使用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.最长的时间,因为 WordPress 甚至告诉您,这是您应该用来集成 WordPress 功能的方法,除了它会导致 404 标头,这很奇怪,他们希望您使用这种方法。 Integrating WordPress with Your Website 将 WordPress 与您的网站集成

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!我知道很多人已经回答了这个问题,它已经有了一个公认的答案,但这里有一个很好的方法,可以在您的 WordPress 网站的根目录(或技术上您想要的网站中的任何地方)创建 .php 文件,您可以浏览它无需 404 标头即可加载!


Update: There is a way to use wp-blog-header.php without 404 headers, but this requires that you add in the headers manually. 更新:有一种方法可以在没有 404 标头的情况下使用wp-blog-header.php ,但这需要您手动添加标头。 Something like this will work in the root of your WordPress installation: 像这样的东西将在您的 WordPress 安装的根目录中工作:

 <?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.只是为了向大家更新这一点,这种方法需要的代码少一点,但这取决于您使用哪种方法。

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.如果您像我一样,有时希望能够在 CMS 中不存在的页面中引用 WordPress 功能。 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() .这实际上很简单,只需使用 PHP require()包含wp-blog-header.php文件即可。

Here's an example that uses a query string to generate Facebook Open Graph (OG) data for any post.这是一个使用查询字符串为任何帖子生成 Facebook Open Graph (OG) 数据的示例。

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:http://example.com/yourfilename.php?1这样的链接为例,其中1是我们要为其生成 OG 数据的帖子的 ID:

Now in the contents of yourfilename.php which, for our convenience, is located in the root WordPress directory:现在在yourfilename.php的内容中,为方便起见,它位于根 WordPress 目录中:

<?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.我们可以创建一个特殊的模板并编辑永久链接结构来做到这一点,但由于它只需要一个页面,并且因为我们不希望客户端从 CMS 中删除它,这似乎是更简洁的选择。


EDIT 2017: Please note that this approach is now deprecated编辑 2017:请注意,此方法现已弃用

For WordPress installations from 2016+ please see How can I add a PHP page to WordPress?对于 2016 年以上的 WordPress 安装,请参阅如何将 PHP 页面添加到 WordPress? for extra parameters to include before outputting your page data to the browser.在将页面数据输出到浏览器之前要包含的额外参数。

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.要运行此代码,您需要从后端选择“mytemplate”作为页面的模板。

Please see this link for getting the correct details https://developer.wordpress.org/themes/template-files-section/page-template-files/ .请参阅此链接以获取正确的详细信息https://developer.wordpress.org/themes/template-files-section/page-template-files/

Any answer did not cover if you need to add a PHP page outside of the WordPress Theme.如果您需要在 WordPress 主题之外添加 PHP 页面,则任何答案均未涵盖。 This is the way.这就是方法。

You need to include wp-load.php.您需要包含 wp-load.php。

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

Then you can use any WordPress function on that page.然后您可以在该页面上使用任何 WordPress 功能。

You will want to take a look in to WordPress' plugin API.您将需要查看 WordPress 的插件 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.这解释了如何“挂钩”和“过滤”到 WordPress 机制的不同部分,因此您几乎可以在任何给定时间的任何地方执行自定义 PHP 代码。 This hooking, filtering, and custom code authoring can all take place in your functions.php file in any of your themes.这种挂钩、过滤和自定义代码创作都可以在您的任何主题的 functions.php 文件中进行。 Happy coding :)快乐编码:)

The best way to add PHP pages in WordPress to Page Template in the theme or child-theme folder.将 WordPress 中的 PHP 页面添加到themechild-theme文件夹中的Page Template的最佳方法。

How to create Page Template in WordPress.如何在 WordPress 中创建Page Template

Create a file named template-custom.php and put it in /wp-content/theme/my-theme/ .创建一个名为template-custom.php的文件并将其放入/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 更多细节

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 文件,例如(/wp-content/themes/your_active_theme/) ,然后您可以从 wp-admin 添加新页面并从页面模板选项中选择此页面模板。

<?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.还有另一种方式,例如您可以将文件包含在 functions.php 中并从中创建短代码,然后您可以像这样将该短代码放入您的页面中。

// 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] .然后你可以在 wp-admin 侧页面中使用这个短代码,像这样[abc]

If you don't want to deal with the WordPress API, then Adam's answer is really the best one.如果您不想处理 WordPress API,那么 Adam 的答案确实是最好的答案。

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.如果您愿意处理 API,我建议您使用“模板重定向”钩子,这将允许您将特定 URL 或页面指向任意 PHP 文件,同时仍然可以访问 WordPress。

The widely accepted answer by Adam Hopkinson is not a fully automated method of creating a page! Adam Hopkinson广泛接受的答案不是创建页面的全自动方法! It requires a user to manually create a page in the back-end of WordPress (in the wp-admin dash).它需要用户在 WordPress 的后端(在 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.此外,这里其他一些被广泛接受的答案涉及在 WordPress 之外创建一个静态页面,然后只包含一些 WordPress 功能来实现主题页眉和页脚。 While that method may work in some cases, this can make integrating these pages with WordPress very difficult without having all its functionality included.虽然该方法在某些情况下可能有效,但如果不包含其所有功能,这会使将这些页面与 WordPress 集成变得非常困难。

I think the best, fully automated, approach would be to create a page using wp_insert_post and have it reside in the database.我认为最好的、完全自动化的方法是使用wp_insert_post创建一个页面并将其驻留在数据库中。 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一个例子和一个很好的讨论,以及如何防止用户意外删除页面,可以在这里找到: 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).坦率地说,我很惊讶这种方法还没有被提及作为这个流行问题的答案(它已经发布了 7 年)。

Create a page call it my-page.php and save it under your theme directory.创建一个名为 my-page.php 的页面并将其保存在您的主题目录下。 Now, edit this php file and write the following line at the top of the page现在,编辑此 php 文件并在页面顶部写入以下行

<?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.在自定义页面定义行下编写您的 PHP 代码,您可以调用您的其他 WP 模板,此文件中的函数。

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

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.由于这是我的页面,您需要从 WordPress 管理面板创建一个页面。 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.如果它是在自定义 php 页面中编写的,您可以完全跳过描述。

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.转到 [wordpress][1] 创建的 slug(永久链接)并查看页面。

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.您还可以在主题目录中创建一个名为page-my-custom-page.php的文件,并使用my-custom-page slug 发布一个页面。
it is also possible to use wp functions to show page details (like the_content() to show that page contents).也可以使用 wp 函数来显示页面详细信息(如the_content()来显示该页面内容)。

now you can access that page using example.com/my-custom-page .现在您可以使用example.com/my-custom-page访问该页面。

I'm not sure if it's an appropriate way, but tested and worked in WP 5.7.3我不确定这是否是一种合适的方式,但在 WP 5.7.3 中进行了测试和工作

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).除了创建自定义模板文件并将该模板分配给页面(如已接受答案中的示例中)之外,还有一种方法可以使用 WordPress 用于加载模板(模板层次结构)的模板命名约定。

Create a new page and use the slug of that page for the template filename (create a template file named page-{slug}.php ).创建一个新页面并使用该页面的 slug 作为模板文件名(创建一个名为page-{slug}.php的模板文件)。 WordPress will automatically load the template that fits to this rule. WordPress 将自动加载符合此规则的模板。

Try this:尝试这个:

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

Rename the new file as templatename.php (where templatename is what you want to call your new template). 将新文件重命名为templatename.php(其中templatename是您要称为新模板的名称)。 To add your new template to the list of available templates, enter the following at the top of the new file: 要将新模板添加到可用模板列表中,请在新文件顶部输入以下内容:

You can modify this file (using PHP) to include other files or whatever you need. 您可以修改该文件(使用PHP)以包括其他文件或所需的任何文件。

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. 然后在WordPress博客中创建一个新页面,在页面编辑屏幕中,您会在右侧的Attributes小部件中看到一个Template下拉列表。 Select your new template and publish the page. 选择您的新模板并发布页面。

Just create a page-mytitle.php file to the folder of the current theme, and from the Dashboard a page "mytitle" .只需在当前主题的文件夹中创建一个page-mytitle.php文件,然后从仪表板创建一个页面"mytitle"

Then when you invoke the page by the URL you are going to see the page-mytitle.php.然后当您通过 URL 调用页面时,您将看到 page-mytitle.php。 You must add HTML, CSS, JavaScript, wp-loop, etc. to this PHP file ( page-mytitle.php ).您必须向此 PHP 文件 ( page-mytitle.php ) 添加 HTML、CSS、JavaScript、wp-loop 等。

You can create the template in Theme Folder than after place your php code in that template file.If You will be required some files for that than you can include that files in that template.See below. 您可以在主题文件夹中创建模板,而不是将您的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();

As long as you store your php file in the wp-content folder, ie inside of a theme or a plugin, it only needs this to get full WP-Power inside the file:只要您将 php 文件存储在 wp-content 文件夹中,即在主题或插件中,它只需要在文件中获得完整的 WP-Power:

$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.之后你就可以正常使用 WP 功能了。 I use this for example in my lyrics plugin to create a printable personalized PDF on the fly.例如,我在我的歌词插件中使用它来即时创建可打印的个性化 PDF。

<?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(); ?>

You can name your file "newpage.php" - put it in your theme directory in wp-content .您可以将文件命名为“newpage.php” - 将其放在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.您可以将其设为页面模板(请参阅http://codex.wordpress.org/Pages... ),也可以将其包含在主题中的 PHP 文件之一中,例如 header.php 或 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 http://codex.wordpress.org/Pages#Creating_Your_Own_Page_Templates

You can also directly use the PHP page, like to create the PHP page and run with full path.您也可以直接使用 PHP 页面,比如创建 PHP 页面并以完整路径运行。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM