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

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

我该怎么做呢?

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


当前回答

我知道这是个老问题,但没人这么说过: 您还可以在theme目录中创建一个名为page-my-custom-page.php的文件,并使用my-custom-page slug发布一个页面。 也可以使用wp函数来显示页面细节(如the_content()来显示页面内容)。

现在您可以使用example.com/my-custom-page访问该页面。

我不确定这是否是一种合适的方式,但在WP 5.7.3中进行了测试和工作

其他回答

只需在当前主题的文件夹中创建一个page-mytitle.php文件,并从仪表板中创建一个page "mytitle"。

然后,当您通过URL调用页面时,您将看到页面-mytitle.php。您必须将HTML, CSS, JavaScript, wp-loop等添加到这个PHP文件(page-mytitle.php)。

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

只要你将你的php文件存储在wp-content文件夹中,即在一个主题或插件中,它只需要在文件中获得完整的WP-Power:

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

在此之后,您可以以通常的方式使用WP函数。例如,我在我的歌词插件中使用它来创建一个可打印的个性化PDF文件。