WordPress comes with a lot of handy tools that let you have URLs and paths to some folders without having to hardcode them, such as the content_url()
and get_stylesheet_directory()
functions for the URL to your content folder and the absolute path to your current theme folder, repectively. You can see a list of all these functions in the Codex.
However, if we search for some function to retrieve the absolute path of the admin folder, we’re lost. We have admin_url()
, get_admin_url()
, network_admin_url()
and get_network_admin_url()
but those only gives us URLs, not paths. Our only answer is to create our own function.
Here’s How You Do It
Of course you can use something like ABSPATH . '/wp-admin'
, but that doesn’t offer any guarantees in case the admin folder were to be renamed at some point, let’s say manually, by a plugin, or with some rewrite rule. There’s a lot of ways thing can go wrong using that method, especially if you’re distributing your code.
What I suggest as a more proper solution is to create a function like this inside your plugin or theme:
What we’re doing here is replacing the base URL of our site with the ABSPATH
constant, which contains the full path to the root folder of your WordPress installation, thus leaving the /wp-admin
part (or whatever it’s called) intact. We obtain the name of the admin folder dynamically, without the need to hardcode it at any point.
You can also get the path for the network admin by just replacing the call to get_admin_url()
with get_network_admin_url()
.
Hope this helps 🙂
The wp-admin filesystem path is NOT meant to be changed. However, the admin URL can be changed and mapped to the internal directory path via a server config directive or filesystem link.
Your solution assumes that the URL corresponds to a directory in the underlying filesystem, but this might not be the case.
You make a pretty valid point, but I see that more as an edge-case than a common scenario. However, I’ll take a look into it and try to improve the solution. Thanks for your comment 🙂