Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I've written several plugins using the structure :

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

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.

share|improve this question

2 Answers 2

up vote 3 down vote accepted

In a subdirectory within your plugin directory you can use the following code:

$this->plugin_location = plugin_dir_url(dirname(__FILE__));
share|improve this answer
    
This is a more direct answer , thanks!!! –  setterGetter Oct 25 '12 at 11:45
    
Thanks a lot mate.. just what i needed ;) –  Sagive SEO Sep 17 '13 at 3:26

Your main plugin controller or setup method should set these variables, and it should make them public:

// Location: /plugins/plugin-name/php/class.Plugin_Controller.php
class Plugin_Controller {

    /**
     * Plugin instance.
     *
     * @see get_instance()
     * @type object
     */
    protected static $instance = NULL;

    /**
     * URL to this plugin's directory.
     *
     * @type string
     */
    public $plugin_url = '';

    /**
     * Path to this plugin's directory.
     *
     * @type string
     */
    public $plugin_path = '';

    /**
     * Access this plugin’s working instance
     *
     * @wp-hook plugins_loaded
     * @since   2012.10.23
     * @return  object
     */
    public static function get_instance() 
    {
        NULL === self::$instance and self::$instance = new self();

        return self::$instance;
    }

    /**
     * Used for regular plugin work.
     *
     * @wp-hook plugins_loaded
     * @since   2012.10.23
     * @return  void
     */
    public function plugin_setup() 
    {
        $this->plugin_url  = plugins_url( '/', dirname( __FILE__ ) );
        $this->plugin_path = plugin_dir_path( dirname( __FILE__ ) );
    }
}

Now all other classes can access these variables with

Plugin_Controller::get_instance()->plugin_path;
Plugin_Controller::get_instance()->plugin_url;

Use plugin_dir_path() and plugins_url(), and keep the hard coded strings in a central position where they are easy and fast to find.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.