Get plugin_dir_url() from one level deep within plugin

I’ve written several plugins using the structure :

/plugins/myplugin/myplugin.php
/plugins/myplugin/class/class-myclass.php

Read More

So as to take advantage of OO and overall structuring my code

From within the class file there are times I need to get the URL of the base plugin… I have been using the following, but I’m sure there’s a better way:

$this->plugin_location = substr(plugin_dir_url(__FILE__),0, strrpos(plugin_dir_url(__FILE__), "/",-2)) . "/";

Another idea I toyed with was having an additional singleton class that stores all of the settings for the plugin and adding an abstraction layer via the class files.

Any help is greatly appreciated.

Related posts

Leave a Reply

2 comments

  1. 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.