我想为我的WordPress博客创建一个自定义页面,将在其中执行我的PHP代码,同时保留整体网站CSS/主题/设计的一部分。

PHP代码将使用第三方api(因此我需要包括其他PHP文件)。

我该怎么做呢?

注:我没有特定的需要与WordPress API交互-除了包括某些其他PHP库,我需要我没有其他依赖的PHP代码,我想包括在WordPress页面。所以很明显,任何不需要学习WordPress API的解决方案都是最好的。


当前回答

创建模板页面是正确的答案。为此,只需将其添加到您在主题文件夹内创建的页面中:

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

为了运行这段代码,您需要从后端选择“mytemplate”作为页面的模板。

请查看此链接以获得正确的详细信息https://developer.wordpress.org/themes/template-files-section/page-template-files/。

其他回答

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

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

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

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

坦率地说,我很惊讶这个方法没有被提到作为这个流行问题的答案(它已经发布了7年)。

试试这个:

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

如果你不想使用WordPress API,那么Adam的答案是最好的。

如果您愿意使用API,我建议您使用“template-redirect”钩子,它允许您在访问WordPress的同时将特定的URL或页面指向任意的PHP文件。

任何答案都不包括如果你需要在WordPress主题之外添加一个PHP页面。就是这条路。

您需要包含wp-load.php。

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

然后你就可以使用该页面上的任何WordPress功能了。