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 );
4 Comments
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?
Frederico,
Yes, if you want to have options that are admin editable, then you should save them to the database. Here is a short tutorial on how to create your own admin interfaces inside the WordPress dashboard and here is how to create a form that saves the settings to the WordPress options table
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.