Function and usage of get_network_option() in wordpress


Answers ( 1 )


    The get_network_option() function in WordPress is a useful tool for retrieving options from a multisite network. This function is particularly relevant when you are working with a WordPress multisite installation, where multiple websites (sites) are managed under a single WordPress installation. Here's a detailed explanation of this function:

    Function Prototype

    get_network_option( int $network_id, string $option, mixed $default_value = false ): mixed

    Function Description

    • Purpose: get_network_option() retrieves the value of a specified option from a WordPress multisite network.

    • Use Case: It's commonly used when you want to fetch network-wide settings or preferences that are not specific to a single site within the network.


    1. $network_id (int, required):

      • This is the ID of the network from which you want to retrieve the option.
      • If you set it to null, it defaults to the current network ID, which is useful when you're working within the context of the current network.
    2. $option (string, required):

      • The name of the option you wish to retrieve.
      • This should be the raw option name without SQL escaping.
    3. $default_value (mixed, optional):

      • This is the value to return if the specified option does not exist in the database.
      • Default value is false, meaning if the option is not found, false will be returned.

    Return Value

    • The function returns the value of the specified option.
    • The type of the return value can be mixed (string, array, object, etc.) depending on what the actual value of the option is.
    • If the option does not exist and a default value is provided, the default value is returned.

    Usage Example

    Consider a multisite network where you want to retrieve a network-wide setting, such as a custom option named "my_custom_network_option":

    $network_id = 1; // Assuming network ID is 1
    $option_name = "my_custom_network_option";
    $default_value = "default"; // Default value if the option doesn't exist
    // Retrieve the option value
    $option_value = get_network_option( $network_id, $option_name, $default_value );
    // Use the option value
    echo $option_value;

    In this example, the function will attempt to fetch the value of "my_custom_network_option" from the network with an ID of 1. If the option doesn't exist, it will return "default".

    Related Function

    • get_option(): This function is similar but is used for retrieving options for a single site within a WordPress installation, not for the entire network.

    Using get_network_option() effectively allows for the management and retrieval of settings that are applicable across the entire network in a WordPress multisite setup, which is crucial for maintaining consistency and control over network-wide configurations.

Leave an answer