这里有一个解决方案,它将返回相对于文件位置的URL,以及指示文件所在位置的字符串,即mu插件/插件/主题。
此代码改编自get_url_from_dir()
在meta box库中使用CMB2.
/**
* Converts a system file path to a URL.
* Returns URL and the detected location of the file.
*
* Based on get_url_from_dir() via CMB2
* @link https://github.com/CMB2/CMB2
*
* @param string $file file path to convert.
* @return string Converted URL.
* @return array|bool (on error)
* array
* $url string Converted URL.
* $location string location of dir (mu-plugins, plugins, theme)
*
*/
function wpse_get_url_info_from_file( $file ) {
$file = wp_normalize_path( $file );
$test_dir = pathinfo( $file );
if ( ! $test_dir ) {
return false;
}
$test_dir = trailingslashit( $test_dir[\'dirname\'] );
// Test if we are in the mu-plugins dir.
if ( 0 === strpos( $test_dir, wp_normalize_path( WPMU_PLUGIN_DIR ) ) ) {
return [
\'url\' => trailingslashit( plugins_url( \'\', $file ) ),
\'location\' => \'mu-plugins\'
];
}
// Test if we are in the plugins dir.
if ( 0 === strpos( $test_dir, wp_normalize_path( WP_PLUGIN_DIR ) ) ) {
return [
\'url\' => trailingslashit( plugins_url( \'\', $file ) ),
\'location\' => \'plugins\'
];
}
// Now let\'s test if we are in the theme dir.
$theme_root = wp_normalize_path( get_theme_root() );
if ( 0 === strpos( $file, $theme_root ) ) {
// Ok, then use get_theme_root_uri.
$url = set_url_scheme(
trailingslashit(
str_replace(
untrailingslashit( $theme_root ),
untrailingslashit( get_theme_root_uri() ),
$test_dir
)
)
);
return [
\'url\' => $url,
\'location\' => \'theme\'
];
}
}
例如,如果我们有一个名为
wpse
居住在
plugins-directory/wpse
还有一个主题
my-theme
, 我们可以在插件或主题中使用以下代码将
admin_image_upload.js
文件,它位于插件和主题的不同目录中。
add_action( \'wp_enqueue_scripts\', \'wpse_enqueue_js_based_on_location\' );
function wpse_enqueue_js_based_on_location() {
$url_info = wpse_get_url_info_from_file( __FILE__ );
//exit ( print_r( $url_info ) );
// Bail if something is wrong.
if ( ! $url_info ) {
return;
}
// Bail if something is wrong.
if ( ! isset( $url_info[\'url\'] ) || ! isset( $url_info[\'location\'] ) ) {
return;
}
// Enqueue the JS based on detected location of the file.
if ( \'plugins\' === $url_info[\'location\'] ) {
wp_enqueue_script( \'wpse-js\', plugins_url( \'/admin_image_upload.js\', __FILE__ ) );
} elseif ( \'theme\' === $url_info[\'location\'] ) {
wp_enqueue_script( \'wpse-js\', get_template_directory_uri() . \'/libs/my_lib/admin_image_upload.js\' );
}
}
从的根目录中的文件使用上述代码时
wpse
插件,
$url_info
将如下所示:
Array(
[url] => http://example.com/wp-content/plugins/wpse/
[location] => plugins
)
如果我们在一个主题的
functions.php
,
$url_info
将如下所示:
Array(
[url] => http://example.com/wp-content/themes/my-theme/
[location] => theme
)