Wordpress - Get plugin_dir_url() from one level deep within plugin
In a subdirectory within your plugin directory you can use the following code:
$this->plugin_location = plugin_dir_url(dirname(__FILE__));
You should make all of your classes independent of their actual location, so you can move them around easily and maybe reuse them in other projects.
I would create a class that tells the other classes what path or URL to use, let it implement an interface so you can reuse the other classes maybe even in a theme or completely outside of WordPress.
Example for the interface:
interface DirectoryAddress
{
/**
* @return string Dir URL with trailing slash
*/
public function url();
/**
* @return string Dir path with trailing slash
*/
public function path();
}
The concrete implementation in your plugin could look like this:
class PluginDirectoryAddress implements DirectoryAddress
{
private $path;
private $url;
public function __construct( $dirpath )
{
$this->url = plugins_url( '/', $dirpath );
$this->path = plugin_dir_path( $dirpath );
}
/**
* @return string Dir URL with trailing slash
*/
public function url() {
return $this->url;
}
/**
* @return string Dir path without trailing slash
*/
public function path() {
return $this->path;
}
}
Now you create an instance of that class in your main plugin file:
$address = new PluginDirectoryAddress( __DIR__ );
And all the other classes have just a dependency on the interface in their constructor, like this:
public function __construct( DirectoryAddress $directory ) {}
They are accessing the URL and the path only from the passed instance now.