Declare constants to easily reference your plugin files

WordPress code

While preparing for my WordCamp Tampa talk, and generally improving the codebase in my own plugins and functionality plugins, I came across a helpful improvement, which came up as a result of wanting to include a file in a different directory.

Because of server restrictions, I was unable to use relative paths to include the file, so I ended up leaning on the advice of Pippin Williamson, as I so often do, and went about setting up constants in the main plugin file.

By defining these constants at the root of the plugin, you can then use them to reach any point in your plugin directory structure. So, to set up these constants, add the following to your plugin file:

Now when you need to include, require or otherwise reference a file in your plugin, you can drop in your constant to get either the path of URL to your plugin directory, such as:

In this way, you also won’t be tempted to try any back-handed ways of getting the plugin URL or path, which may end up breaking the plugin when someone uses a non-standard location for the wp-content folder for example.

Leave a Reply