我有一个 WordPress 框架,可以嵌入到插件、主题或子主题中。为了返回正确的 URL,脚本需要确定它的执行位置。
我相信我可以做一些类似匹配 __FILE__
的事情:
get_template_directory_uri()
(主题),get_stylesheet_directory_uri()
(主题或子主题),或plugin_dir_url( __FILE__ )
(插件)
有没有更好、更可靠的方法?无论如何,我该怎么办?
最佳答案
此函数将返回一个字符串,指示从何处调用它。可能的返回值为 plugin
、mu-plugin
、child-theme
、theme
或 FALSE
如果它不在主题或插件中。
使用此函数时,始终传递 __DIR__
作为参数,例如:where_am_i(__DIR__)
。
/**
* @param string $directory always __DIR__
*/
function where_am_i($directory) {
$current_directory = forward_slashes($directory);
$plugins_directory = forward_slashes(WP_PLUGIN_DIR);
$mu_plugins_directory = forward_slashes(WPMU_PLUGIN_DIR);
$themes_directory = forward_slashes(get_theme_root());
if ( strpos ( $current_directory, $plugins_directory ) !== FALSE ) {
$location = 'plugin';
} elseif ( strpos ( $current_directory, $mu_plugins_directory ) !== FALSE ) {
$location = 'mu-plugin';
} elseif ( strpos ( $current_directory, $themes_directory ) !== FALSE ) {
// Script is in a theme, determine if parent or child
$stylesheet_directory = forward_slashes(get_stylesheet_directory());
if ( is_child_theme() && ( strpos ( $current_directory, $stylesheet_directory ) !== FALSE ) ) {
$location = 'child-theme';
} else {
$location = 'theme';
}
} else {
// not in a theme or plugin
$location = FALSE;
}
return $location;
}
/**
* Handle Windows paths
*/
function forward_slashes($string) {
return str_replace('\\', '/', $string);
}
以下函数 where_am_i_dir()
将为您提供调用它的位置的目录结构,但省略 */wp-content/{$subdir}
。如果它是从 /wp-content/themes/twentyfourteen/libs/script.php
调用的,它将返回 /twentyfourteen/libs
(如果你希望它返回一个尾随的斜杠(当斜杠被过滤时,您可以将其连接到 $directory
)。
第一个参数是 where_am_i()
的返回值,第二个参数始终是 __DIR__
。示例:where_am_i_dir($location, __DIR__)
。
/**
* @param string $location return from where_am_i()
* @param string $directory always __DIR__
*/
function where_am_i_dir($location, $directory) {
if ($location == 'plugin') {
$subdirectory_name = '/plugins';
} elseif ($location == 'mu-plugin') {
$subdirectory_name = '/mu-plugins';
} elseif ($location == 'theme' || $location == 'child-theme') {
$subdirectory_name = '/themes';
} else {
return FALSE;
}
$directory = forward_slashes($directory);
$wp_content_directory = forward_slashes(WP_CONTENT_DIR) . $subdirectory_name;
return str_replace($wp_content_directory, '', $directory);
}
如果您有兴趣,您可以将 where_am_i()
和 where_am_i_dir()
合并到一个函数中,该函数返回包含这两个值的数组。
关于php - 如何判断脚本是否从 WordPress 中的插件、主题或子主题执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23638513/