Function and usage of network_site_url() in wordpress

Question

Answers ( 1 )

    0
    2024-01-08T22:30:53+00:00

    The network_site_url() function in WordPress is used to retrieve the site URL for the current network. Here's a detailed explanation of its functionality and usage:

    Function Signature

    network_site_url( string $path = '', string|null $scheme = null ): string
    

    Function Description

    • Purpose: Retrieves the site URL of the current WordPress network.
    • Behavior:
      • The function returns the site URL with the appropriate protocol.
      • By default, it uses 'https' if is_ssl() is true, indicating that the site is accessed via SSL (Secure Sockets Layer). Otherwise, it uses 'http'.
      • If $scheme is explicitly set to 'http' or 'https', it overrides the is_ssl() check.
      • The $scheme parameter can also be set to 'relative' to omit the protocol part of the URL, useful for relative URLs.
    • Related Function: set_url_scheme() can be used in conjunction with this to set or alter the URL scheme.

    Parameters

    1. $path (string, optional):

      • Description: A path relative to the site URL.
      • Default: An empty string ('').
      • Use: Appends the specified path to the site URL.
    2. $scheme (string|null, optional):

      • Description: Specifies the scheme to give the site URL context.
      • Accepts: 'http', 'https', or 'relative'.
      • Default: null.
      • Use: Determines the protocol (http or https) of the returned URL or returns a protocol-relative URL.

    Return Value

    • Type: string
    • Description: The function returns the site URL link, with any optional path appended to it.

    Sample Usage

    1. Default Use: To get the current network site URL with the appropriate protocol:

      $url = network_site_url();
      
    2. With Path: To append a specific path to the network site URL:

      $url = network_site_url('/my-path/');
      
    3. Specifying Scheme: To explicitly set the URL scheme:

      // Using HTTPS
      $url = network_site_url('', 'https');
      
      // Using HTTP
      $url = network_site_url('', 'http');
      
      // Using a relative scheme
      $url = network_site_url('', 'relative');
      

    Practical Scenario

    • Use in Multisite Network: In a WordPress multisite setup, network_site_url() is particularly useful for getting the main site URL of the network, regardless of which site within the network the code is running on.

    This function is essential for WordPress development, especially in environments where multiple sites are running under a single WordPress installation.

Leave an answer