是否有一个函数可以返回plugin_dir_path
但它对插件/主题是不可知的?JS脚本需要作为资源排队,因此,您不能包括其在服务器上的路径,例如/var/www/html/wordpress/thing/thing2/script.js
, 它必须是http://www.example.com/thing/thing2/script.js
对应方
如何获取链接路径以用于JS脚本等资源?
虽然@butlerblog的答案有效,但我发现它不必要地复杂。我已经检查过了,site_url
将始终为您提供当前站点的链接,它将为您解析架构,无论是否http
或https
, 因此,它没有任何问题。
我编写了一个更简单、更容易理解的函数:
/**
* Retrieves the full front-facing URL for a given path. In other words, it transforms an absolute path
* into an URI.
*
* Note: when allowing direct access to your files, if there is any I/O (there shouldn\'t be, but, you know) operations,
* you must check whether or not ABSPATH is defined.
*
* @see https://stackoverflow.com/a/44857254/12297763
*
* @param string $from An absolute path. You can just call this function with the parameter __FILE__ and it will give you a front-facing URI for that file.
* @param boolean $strict Flag that the function uses to see if it needs to do additional checks.
*
* @return string|false Returns a string in the form of an URI if all checks were passed or False if checks failed.
*/
function getURIFromPath( $from, $strict = False )
{
if( $strict ) {
if( !\\file_exists( $from ) ) {
return False;
}
}
$abspath = untrailingslashit( ABSPATH ) ;
$directory = dirname( $from );
return str_replace( "//", "\\\\", site_url() . str_replace( $abspath, \'\', $directory ) );
}
命名它的理由URI...
在任何情况下都不需要构建包含PHP文件的链接。如果您将代码作为包分发,并且不能依赖框架的/主插件常量,则需要使用此选项。换句话说,当您不知道软件包的安装路径时,请使用此选项。它的工作原理与CSS类似../
(始终是相对的)。这是一种骇人的方式;但不幸的是,没有一个WP函数可以同时完成这两个任务(主题和/或插件)。这只是一个非此即彼的提议。
表面上看,你会认为这并不困难。您只需获取路径并将其与网站URL或类似的内容进行比较。但当WP安装在根目录以外的其他位置(例如目录)时,您会遇到问题。
如果您在函数中查看我的设置,“else”条件很简单。如果可湿性粉剂总是在根部,那将是你所需要做的全部。其他一切都是为了处理另一种可能性(WP位于目录或更低的目录中)。
在这种情况下,它会分解站点URL,以确定是否存在不止根域(大于3的数组)。如果是这样的话,它将遍历我们从explode()
过程我们可以跳过数组的前三个元素,因为它们应该是域的根(https://example.com). 然后构建路径(如果下面不止一个目录)。
使用它可以去掉根URL下面的所有内容,这样就可以得到一个干净的URL。然后将路径附加到文件。
function my_get_file_url_path() {
// Account for WP being installed in a directory.
$path_info = \'\';
$site_url = site_url();
$url_parts = explode( \'/\', $site_url );
if ( array_count_values( $url_parts ) > 3 ) {
$x = 0;
foreach ( $url_parts as $this_part ) {
if ( $x > 2 ) {
$path_info = $this_part . \'/\';
}
$x++;
}
$site_actual_url = str_replace( $path_info, \'\', trailingslashit( $site_url ) );
return $site_actual_url . trim( str_replace( $_SERVER[\'DOCUMENT_ROOT\'], \'\', __DIR__ ), \'/\' );
} else {
return str_replace( $_SERVER[\'DOCUMENT_ROOT\'], $site_url, __DIR__ );
}
}
这是一个简单的实用程序函数,它可以准确地实现这里所有人都在寻找的功能,即获取当前插件的根url路径。
function get_plugin_url()
{
$uri = plugin_basename(__DIR__);
$path = explode(\'/\', $uri);
return WP_PLUGIN_URL.\'/\'.$path[0].\'/\';
}
输出示例:https://example.com/wp-content/plugins/your-plugin-slug/