无法从WordPress主题文件夹中包含PHP文件

4
我正在尝试包含一个位于WordPress主题文件根目录下的PHP文件。
例如:localhost/mywordpresssite/wp-content/themes/mytheme/myfile.php 我正在尝试从位于“部件>共享”下的文件footer.php中调用它。
例如:localhost/mywordpresssite/wp-content/themes/mytheme/parts/shared/footer.php 我可以确认,在浏览器中访问完整URL时,该文件确实显示出来,因此路径是正确的。
我已经尝试了多种不同的方式无法包含此文件:
1)首选方式-使用样式表目录URI
<?php
    $stylesheet_root = get_stylesheet_directory_uri();
    include $stylesheet_root.'/myfile.php';
?>

这应该能找到样式表的URI并找到文件,但我却得到了这个错误信息:

找不到合适的包装器

我知道这是因为它不安全,而且默认情况下allow_url_include被关闭了,那么最好的方法是什么呢?2)在URL中编码以向上爬两个目录 这似乎是一个相当明智的方法,因为文件将始终相对两个目录而言。但这似乎没有任何作用。它仍然在同一个目录中寻找文件:
<?php include '../../myfile.php'; ?>

3) 只需在代码中写死这个愚蠢的东西。

然而,即使在此处放置的URL已经在浏览器中测试并成功加载了正确的文件,但它仍然无法将其加载到包含文件中...

<?php include 'localhost/mywordpresssite/wp-content/themes/mytheme/twitter-feed.php'; ?>

出现错误:

警告:include(localhost/mywordpresssite/wp-content/themes/mytheme/twitter-feed.php):无法打开流:在/Applications/MAMP/htdocs/mywordpresssite/wp-content/themes/mytheme/parts/shared/footer.php的第3行没有此类文件或目录

还有什么我可以做的吗?


那么 include( 'twitter-feed.php' ) 是什么意思?它会产生什么结果? - BenM
2
我认为你误解了include的含义,它与你网站的URL无关,而是与你服务器的目录有关。因此,将完整的路径硬编码后看起来会更像include '/var/www/mywordpresssite... - CᴴᵁᴮᴮʸNᴵᴺᴶᴬ
还在寻找解决方案吗? - rnevius
1
get_stylesheet_directory_uri会获取一个URI,但你需要一个本地文件系统路径。而且也有一个函数可以实现这个功能 - get_stylesheet_directory - CBroe
3个回答

7

您正在尝试通过URL进行include。 您需要通过文件路径(而不是URI)进行include

<?php
    $stylesheet_root = get_stylesheet_directory();
    include( $stylesheet_root . '/myfile.php' );
?>

请在文档中了解更多关于get_stylesheet_directory()函数的信息。


0

看起来你正在使用相对路径,即你没有以 / 开头。路径应该类似于(unix/mac)/var/www/mywordpresssite/wp-content/themes/mytheme/twitter-feed.php

你可以使用 include(__DIR__ . '/myfile.php');,这样你的包含文件始终是相对于当前脚本所在的目录。

由于某种原因,使用 ../../myfile.php 无法用于包含文件。


-2

我将hello.php放在我的主题根目录中(与footer.php所在的位置相同),以下代码放在footer.php的结尾处即可:

<?php include (TEMPLATEPATH . '/hello.php'); ?>

1
似乎TEMPLATEPATH已经被弃用了,实际上我们应该使用get_template_directory()代替。 - Vinch

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接