In recent changes to WordPress code, users are more than ever able to customize folder and file locations. [Edit: Refers to WordPress 2.6] The wp-config.php file can now be located one directory up from the one containing WordPress. The wp-content folder can be moved arbitrarily, as can (separately) the plugins folder. What’s a poor plugin author to do in keeping track of these ever-moving targets?
When those last two folders are moved, it is done by defining specific constants: WP_CONTENT_DIR and WP_CONTENT_URL for the wp-content folder, and WP_PLUGIN_DIR and WP_PLUGIN_URL for the plugins folder. In plugins it’s best to use these, except that they are not defined in a default setup, and don’t exist in earlier versions of WordPress.
The solution, fortunately, is simple: Check if they are already defined. If they’re not, then the folders are in the default locations and you can define them accordingly. Then just use the constants as normal. Here’s the code; just drop this somewhere in the beginning of your plugin:
if ( ! defined( 'WP_CONTENT_URL' ) )
define( 'WP_CONTENT_URL', get_option( 'siteurl' ) . '/wp-content' );
if ( ! defined( 'WP_CONTENT_DIR' ) )
define( 'WP_CONTENT_DIR', ABSPATH . 'wp-content' );
if ( ! defined( 'WP_PLUGIN_URL' ) )
define( 'WP_PLUGIN_URL', WP_CONTENT_URL. '/plugins' );
if ( ! defined( 'WP_PLUGIN_DIR' ) )
define( 'WP_PLUGIN_DIR', WP_CONTENT_DIR . '/plugins' );
There are a couple things to note:
- By defining these, you might actually fix problems in other plugins — ones that assume these are defined and call them without checking.
- I recommend not using the older
PLUGINDIRconstant at all. It is both obsolete and problematic. UseWP_PLUGIN_DIRinstead. - You might be tempted to set
WP_PLUGIN_DIRas something likedirname(dirname(__FILE__)). Don’t. First, it’s inefficient, as it unnecessarily callsdirname()twice. Second, I’ve seen (albeit unusual) situations where it caused problems*.
So. Not so complicated after all — it’s just one of those rote things that’s helpful to know. Use those four constants and you shouldn’t go wrong finding the right paths in WordPress.
