编辑与@s\\u ha\\u dum交谈,操作系统和路径之间存在问题,Windows使用反斜杠,所以我们需要对其进行补偿
因为OP需要返回一个布尔值,所以我们需要一个函数来返回true或false,所以我们可以编写两个单独的函数来覆盖这两个基,或者只选择一个并使用它。这种方法也有其缺点,因为它不适用于加载在插件和主题文件夹之外的文件
让我们看一个条件,如果从主题加载文件,该条件将返回true
function is_file_in_theme( $file_path = __FILE__ )
{
// Get the them root folder
$root = get_theme_root();
// Change all \'\\\' to \'/\' to compensate for localhosts
$root = str_replace( \'\\\\\', \'/\', $root ); // This will output E:\\xampp\\htdocs\\wordpress\\wp-content\\themes
// Make sure we do that to $file_path as well
$file_path = str_replace( \'\\\\\', \'/\', $file_path );
// We can now look for $root in $file_path and either return true or false
$bool = stripos( $file_path, $root );
if ( false === $bool )
return false;
return true;
}
我们也可以对插件执行同样的操作
function is_file_in_plugin( $file_path = __FILE__ )
{
// Get the plugin root folder
$root = WP_PLUGIN_DIR;
// Change all \'\\\' to \'/\' to compensate for localhosts
$root = str_replace( \'\\\\\', \'/\', $root );
// Make sure we do that to $file_path as well
$file_path = str_replace( \'\\\\\', \'/\', $file_path );
// We can now look for $root in $file_path and either return true or false
$bool = stripos( $file_path, $root );
if ( false === $bool )
return false;
return true;
}