Paulund
2013-06-17 #wordpress

Get Current Plugin URL

During WordPress plugin development you will need to include any Javascript or CSS files used by plugin inside the plugin folder, this means that it can be used exactly the same way on any theme you have installed. To include Javascript or CSS files from a plugin you need to use the wp_enqueue_script() or the wp_enqueue_style() functions. Both of these functions need a number of different parameters but the first 2 parameters in these function are important the handle and the source of the Javascript or CSS file.


wp_enqueue_style('stylsheet', 'http://www.example.com/stylesheet.css' );

As your Javascript or CSS file will be inside your plugin you need to give this function the location to where your file is stored. As all plugins in WordPress are stored in the same location (in the wp-content folder) this should be easy to get file location.


wp_enqueue_style('stylsheet', 'http://www.example.com/wp-content/plugins/example-plugin/css/stylesheet.css' );

This will work fine but it's not best practice, for example you can only use this on the one domain, you can't move this plugin inside the mu-plugins folder and you can't change the name of the plugin folder. So to get around these problems WordPress comes with a very useful function called plugins_url(), you give this function the filepath and it will return with the URL to this plugin. It is very useful to use when you need to include Savascript or CSS files in your plugin.


$url = plugins_url( $path, $plugin );

If you want to include a stylesheet from within a plugin the best way to do this is to use the global variable FILE as the second parameter, this will always return the URL root of the plugin. So if your stylesheet is in a css folder on the root of your plugin you will enqueue it by using the following code.


wp_enqueue_style('stylsheet', plugins_url( 'css/stylesheet.css', __FILE__ ) );