Paths For Building WordPress Themes or Plugins

When tinkering with the code that runs WordPress it’s very important to get the correct path to a file. Of course it is or else the files can’t be found and your new functionality won’t work.

According to the Codex –

In Version 2.6, users were given the ability to move their /wp-content/ directory to anywhere they want, and many users already keep all WordPress files (like /wp-admin/ and /wp-includes/) in an unusual place.

In case you’ve moved the files for your WP installation, you probably have a good handle on paths and how to traverse them. For those who don’t, it can be a hair-pulling experience to find the right path. Once the right path is found, work can continue.

WordPress Paths

To help avoid those DUH! moments, here are some functions and constants that WordPress has defined regarding paths. Once you’re familiar with these functions, writing useful and working code should become easier. Optional parameters may be of use in modifying the output for several of the following templates, including $path, $file or $scheme.

Usage: plugin_basename(__FILE__); Returns: the name of the plugin and file, such as “myPlugin/myPlugin.php”
Usage: get_theme_root(); Returns: path to themes directory. No trailing slash.
Usage: get_theme_root_uri(); Returns: URI for themes directory. No trailing slash.
Usage: get_theme_roots(); Returns: Themes directory with a leading slash, like “/themes”.
Usage: site_url(); Returns: Site directory with no trailing slash. OR
Usage: admin_url(); Returns: Admin directory with trailing slash.
Usage: content_url(); Returns: Content directory with trailing slash.
Usage: plugins_url(); Returns: Plugins directory with trailing slash.
Usage: includes_url(); Returns: Includes directory with trailing slash.
Usage: home_url(); Returns: Home directory with no trailing slash.
ABSPATH (constant)
Usage: ABSPATH. Returns: Home directory with no trailing slash.
Usage: TEMPLATEPATH. Returns: Path to current theme with no trailing slash.

There are a few more functions for multisite installations and backwards capability specified in the Codex.

PHP Paths

Some PHP functions worth noting –

  • __FILE__ returns the filename of the script that is currently being run
  • dirname() returns parent directory’s path for a given filename with no trailing slash
  • basename() returns the filename component of path without any parent directories
  • getcwd() returns current working directory

Use the functions or constants indicated to build your paths instead of hard-coding them. You’ll save yourself a LOT of trouble when it comes time to move your WordPress installation to a new server or directory.