我想为我的WordPress博客创建一个自定义页面,将在其中执行我的PHP代码,同时保留整体网站CSS/主题/设计的一部分。
PHP代码将使用第三方api(因此我需要包括其他PHP文件)。
我该怎么做呢?
注:我没有特定的需要与WordPress API交互-除了包括某些其他PHP库,我需要我没有其他依赖的PHP代码,我想包括在WordPress页面。所以很明显,任何不需要学习WordPress API的解决方案都是最好的。
我想为我的WordPress博客创建一个自定义页面,将在其中执行我的PHP代码,同时保留整体网站CSS/主题/设计的一部分。
PHP代码将使用第三方api(因此我需要包括其他PHP文件)。
我该怎么做呢?
注:我没有特定的需要与WordPress API交互-除了包括某些其他PHP库,我需要我没有其他依赖的PHP代码,我想包括在WordPress页面。所以很明显,任何不需要学习WordPress API的解决方案都是最好的。
当前回答
你可以在你的活动主题文件夹下添加任何php文件 (/wp-content/themes/your_active_theme/)然后你可以从wp-admin中添加新页面,并从页面中选择这个页面模板 模板的选择。
<?php
/*
Template Name: Your Template Name
*/
?>
还有一种方法,你可以把你的文件 functions。php然后创建短代码然后你可以把它 在页面中像这样进行短代码。
// CODE in functions.php
function abc(){
include_once('your_file_name.php');
}
add_shortcode('abc' , 'abc');
然后你可以像这样在wp-admin侧页中使用这个短代码 (abc)。
其他回答
如果你不想使用WordPress API,那么Adam的答案是最好的。
如果您愿意使用API,我建议您使用“template-redirect”钩子,它允许您在访问WordPress的同时将特定的URL或页面指向任意的PHP文件。
除了创建一个自定义模板文件并将该模板分配给一个页面(就像在已接受答案的例子中),还有一种方法是使用模板命名约定,WordPress用于加载模板(模板层次结构)。
创建一个新页面,并使用该页的slug作为模板文件名(创建一个名为page-{slug}.php的模板文件)。WordPress将自动加载符合此规则的模板。
创建模板页面是正确的答案。为此,只需将其添加到您在主题文件夹内创建的页面中:
<?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(); ?>
我知道这是个老问题,但没人这么说过: 您还可以在theme目录中创建一个名为page-my-custom-page.php的文件,并使用my-custom-page slug发布一个页面。 也可以使用wp函数来显示页面细节(如the_content()来显示页面内容)。
现在您可以使用example.com/my-custom-page访问该页面。
我不确定这是否是一种合适的方式,但在WP 5.7.3中进行了测试和工作