Getting the current site URL in WordPress using get_site_url

The get_site_url function in WordPress returns the URL of the current site. This can be useful for retrieving the base URL of the WordPress site, which can be used to construct links or references to other pages or resources within the site.

By using the get_site_url function, developers can ensure that links and references are always pointing to the correct location, regardless of the site’s URL structure or configuration.

Parameters Accepted by the get_site_url Function

  • $blog_id (int|null), optional. Default value: null. Description: Site ID. Default null (current site).
  • $path (string), optional. Default value: ”. Description: Path relative to the site URL.
  • $scheme (string|null), optional. Default value: null. Description: Scheme to give the site URL context. Accepts ‘http’, ‘https’, ‘login’, ‘login_post’, ‘admin’, or ‘relative’.

Value Returned by the get_site_url Function

The function returns a string which is the site URL link with an optional path appended.

Examples

How to get the site URL

Below is an example of using the get_site_url function to retrieve the site URL in WordPress:

$url = get_site_url();
echo $url;

This code snippet retrieves the site URL using the get_site_url function and then prints the URL to the screen using echo.

How to get the site URL with HTTPS

Here’s an example of using the get_site_url function to retrieve the site URL with the HTTPS protocol:

$url = get_site_url(null, '', 'https');
echo $url;

This code snippet uses the get_site_url function with the parameters null for the site ID, an empty string for the path, and 'https' for the scheme to retrieve the site URL with the HTTPS protocol.

How to get the site URL for a specific site ID

Here’s an example of using the get_site_url function to retrieve the site URL for a specific site ID:

$url = get_site_url(2);
echo $url;

This code snippet uses the get_site_url function with the parameter 2 for the site ID to retrieve the site URL for the specific site with ID 2.

Conclusion

The get_site_url function is a valuable tool for developers working with WordPress websites. It provides a simple and efficient way to retrieve the URL of the current site, which can be used in a variety of applications. By understanding how to properly use this function and its parameters, developers can enhance the functionality and user experience of their WordPress sites.

Whether it’s for building custom themes, creating plugins, or simply optimizing the performance of a website, get_site_url offers a reliable solution for accessing site URLs. With its flexibility and ease of use, this function is a valuable asset for any developer working within the WordPress ecosystem.

Related WordPress Functions