如何将 PHP 页面添加到 WordPress?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2810124/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 07:44:52  来源:igfitidea点击:

How can I add a PHP page to WordPress?

phpwordpress

提问by rutherford

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?

我该如何实现?

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.

注意:我没有与 WordPress API 交互的特定需求 - 除了包含某些其他 PHP 库之外,我需要在想要包含在 WordPress 页面中的 PHP 代码中没有其他依赖项。因此,显然任何不需要学习 WordPress API 的解决方案都是最好的解决方案。

回答by Adam Hopkinson

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

您不需要与 API 交互或使用插件。

First, duplicate post.phpor page.phpin your theme folder (under /wp-content/themes/themename/).

首先,复制post.phppage.php在您的主题文件夹中(在 下/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:

将新文件重命名为templatename.php(其中 templatename 是您要调用的新模板)。要将新模板添加到可用模板列表中,请在新文件的顶部输入以下内容:

<?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 Templatedropdown in the Attributeswidget to the right. Select your new template and publish the page.

然后在您的 WordPress 博客中创建一个新页面,在页面编辑屏幕中,您将在右侧的“属性”小部件中看到一个模板下拉列表。选择您的新模板并发布页面。

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

您的新页面将使用中定义的 PHP 代码 templatename.php

Source: Creating Custom Page Templates for Global Use

来源:创建供全球使用的自定义页面模板

回答by Solomon Closson

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 needfor 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. Also, this assumes that your .php file is within the root of your WordPress site where your wp-config.phpfile is located.

然后您可以在此之后简单地执行任何 WordPress 功能。此外,这假设您的 .php 文件wp-config.php位于您的文件所在的 WordPress 站点的根目录中。

This, to me, is a pricelessdiscovery 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

对我来说,这是一个无价的发现,因为我使用require_once(dirname(__FILE__) . '/wp-blog-header.php');了最长时间,因为 WordPress 甚至告诉您,这是您应该用来集成 WordPress 功能的方法,除了它会导致 404 标头,这是他们想要的奇怪你用这个方法。将 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 标头即可加载!



更新:有一种方法可以在wp-blog-header.phpwp-blog-header.php没有 404 标头的情况下使用,但这需要您手动添加标头。像这样的东西将在您的 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.

只是为了向大家更新这一点,这种方法需要的代码少一点,但这取决于您使用哪种方法。

回答by DrewT

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.

如果您像我一样,有时希望能够在 CMS 中不存在的页面中引用 WordPress 功能。这样,它保持后端特定,不会被客户端意外删除。

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

这实际上很简单,只需wp-blog-header.php使用 PHP包含文件即可require()

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?1where 1is the ID of a post we want to generate OG data for:

以一个链接为例,我们要为其生成 OG 数据的帖子的 IDhttp://example.com/yourfilename.php?1在哪里1

Now in the contents of yourfilename.phpwhich, 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?for extra parameters to include before outputting your page data to the browser.

对于 2016 年以上的 WordPress 安装,请参阅如何将 PHP 页面添加到 WordPress?在将页面数据输出到浏览器之前要包含的额外参数。

回答by DrewT

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/

回答by I am the Most Stupid Person

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

如果您需要在 WordPress 主题之外添加 PHP 页面,则任何答案均未涵盖。这就是方法。

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 功能。

回答by ashish thakor

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

创建一个名为 my-page.php 的页面并将其保存在您的主题目录下。现在,编辑此 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");?>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

由于这是我的页面,您需要从 WordPress 管理面板创建一个页面。转到管理 => 页面 => 添加新

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(永久链接)并查看页面。

回答by Gufran Hasan

The best way to add PHP pages in WordPress to Page Templatein the child-themefolder.

将 WordPressPage Template中的PHP 页面添加到child-theme文件夹中的最佳方法。

How to create Page Templatein WordPress.

如何Page Template在 WordPress 中创建。

Create a file named template-custom.phpand 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

更多细节

回答by Damian Green

The widely accepted answer by Adam Hopkinsonis 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.

Adam Hopkinson广泛接受的答案不是创建页面的全自动方法!它需要用户在 WordPress 的后端(在 wp-admin dash 中)手动创建一个页面。问题是,一个好的插件应该有一个完全自动化的设置。它不应该要求客户手动创建页面。

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.

此外,这里其他一些被广泛接受的答案涉及在 WordPress 之外创建一个静态页面,然后只包含一些 WordPress 功能来实现主题页眉和页脚。虽然该方法在某些情况下可能有效,但如果不包含其所有功能,这会使将这些页面与 WordPress 集成变得非常困难。

I think the best, fully automated, approach would be to create a page using wp_insert_postand 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

我认为最好的、完全自动化的方法是使用创建一个页面wp_insert_post并将其驻留在数据库中。一个例子和一个很好的讨论,以及如何防止用户意外删除页面,可以在这里找到: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 年)。

回答by hsatterwhite

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. This hooking, filtering, and custom code authoring can all take place in your functions.php file in any of your themes. Happy coding :)

这解释了如何“挂钩”和“过滤”到 WordPress 机制的不同部分,因此您几乎可以在任何给定时间的任何地方执行自定义 PHP 代码。这种挂钩、过滤和自定义代码创作都可以在您的任何主题的 functions.php 文件中进行。快乐编码:)

回答by Stephen R

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。