The content_url() WordPress PHP function retrieves the URL to the content directory. This function is especially helpful when you need to reference files and folders inside the content directory, such as plugins, themes, and uploads folders.
Usage
To use the content_url() function, you simply call it with an optional path relative to the content URL. If no path is provided, it will return the URL to the content directory.
echo content_url(); // outputs: http://www.example.com/wp-content
Parameters
- $path (string) – Optional. This is the path relative to the content URL. Default is an empty string (”).
More information
See WordPress Developer Resources: content_url()
This function is integral when referencing the content directory as it takes into account any potential user modifications to the name or location of the directory. Remember not to hardcode this directory as /wp-content
, as changes to the directory’s location or name would break your code.
Examples
Display the URL of the content directory
In this example, we use the content_url() function to output the URL of the content directory.
echo content_url(); // Output: https://example.com/wp-content
Display the URL of the plugins folder
This example shows how to use the content_url() function to retrieve the URL of the plugins folder inside the content directory.
echo content_url('/plugins'); // Output: https://example.com/wp-content/plugins
Use content_url() in a function
You can use content_url() function inside your custom function. Let’s assume we have a function that prints the URL of a specific plugin.
function plugin_url($plugin_name) { echo content_url("/plugins/$plugin_name"); } plugin_url('my-plugin'); // Output: https://example.com/wp-content/plugins/my-plugin
Use content_url() with a renamed content directory
This example shows how content_url() adapts if the content directory has been renamed, for example, to ‘assets’.
echo content_url(); // Output: https://example.com/assets
Use content_url() with a renamed content directory to get plugin URL
If the content directory has been renamed, content_url() will still correctly point to the plugins directory.
echo content_url('/plugins'); // Output: https://example.com/assets/plugins