Wordpress services, tutorials and news

How to find the URL to the plugins folder when creating a plugin

If you’re building a plugin, you will probably get to the point where you would like to include files from the plugin folder. As building a plugin means the code should work no matter how the blog is configured, you should use a function that retrieves the path to the plugin folder, then hardcode only the name of the file that needs to be included. As usual, WordPress comes to the help with a special function that retrieves the path to the plugins folder: plugins_url.

Using plugins_url to retrieve the path to the plugins folder in WordPress

Plugins_url can be used to retrieve the path of images, CSS or Javascript files that are placed inside the plugin folders. We have 3 situations:

  • you also hardcode the folder of the plugin (let’s say the plugin folder is wp-polls and we want the path to the css file): $url = plugins_url(); echo $url; wp_register_style( ‘wps_poll_Stylesheet’, $url . ‘/wps-poll/wps-poll.css’ ); Note: don’t change the plugin folder! Or if you do, remember the change the hardcoded part as well.
  • You let plugins_url to retrieve the path using the $plugin parameter: $url = plugins_url(‘wps-poll.css’, __FILE__); echo $url; wp_register_style( ‘wps_poll_Stylesheet’, $url );
  • If the files are in a subfolder you should use dirname(__FILE__): $url = plugins_url(‘wps-poll.css’, dirname(__FILE__)); echo $url; wp_register_style( ‘wps_poll_Stylesheet’, $url );

Related Posts

4 Comments

  1. Great post. I know it doesnt really have that much to do with it but,.. how do you handle a plugin with its own user-handled css options? Do you give the user some basic style-options you’ve tested so that he can chose what he wants and keep the styles in the db or maybe in an array?

  2. Thanks a lot, I’m currently following lynda.com’s wp plugin tutorial, which is cool but rather basic when you wanna go for something a little bit more complex. This is gonna help me out with it.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Wordpress templates

responsive_wp_468x60