【问题标题】:Cannot include PHP file from Wordpress theme folder无法包含 Wordpress 主题文件夹中的 PHP 文件
【发布时间】:2015-04-14 12:14:06
【问题描述】:

我正在尝试在我的 Wordpress 主题文件的根目录中包含一个 PHP 文件。

例如 localhost/mywordpresssite/wp-content/themes/mytheme/myfile.php

我正在尝试从位于parts > shared 的文件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'; ?>

给出错误:

警告:包括(localhost/mywordpresssite/wp-content/themes/mytheme/twitter-feed.php):无法打开流:/Applications/MAMP/htdocs/mywordpresssite/wp-content/ 中没有这样的文件或目录第 3 行的主题/mytheme/parts/shared/footer.php

我还能做什么?

【问题讨论】:

  • 怎么样:include( 'twitter-feed.php' )?这会产生什么?
  • 我认为您误解了 include,它与您的网站 URL 无关,它与您的服务器目录相关,因此对完整内容进行硬编码看起来更像 include '/var/www/mywordpresssite...
  • 还在寻找解决方案?
  • get_stylesheet_directory_uri 会给你一个 URI,但你需要一个本地文件系统路径。还有一个功能 - get_stylesheet_directory

标签: php wordpress


【解决方案1】:

您正在尝试通过 URL 发送 include。您需要通过文件的路径(不是 uri)include

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

阅读更多关于get_stylesheet_directory() in the docs的信息。

【讨论】:

    【解决方案2】:

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

    您可以使用include(__DIR__ . '/myfile.php');,这样您的包含始终与您的脚本当前所在的目录相关。

    由于某些原因,使用 ../../myfile.php 不适用于包含。

    【讨论】:

      【解决方案3】:

      我将 hello.php 放在我的主题的根文件夹中(footer.php 所在的位置),这在我的 footer.php 末尾对我有用:

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

      【讨论】:

      • 似乎 TEMPLATEPATH 实际上已被弃用,我们应该使用 get_template_directory() 代替
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-08
      • 1970-01-01
      • 2013-02-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多