Function and usage of get_query_var() in wordpress


Answers ( 1 )


    get_query_var() is a function in WordPress used to retrieve the value of a query variable from the WP_Query class. This function is particularly useful when working with custom queries or when you need to fetch specific parameters from the current WordPress query.

    Function Syntax:

    get_query_var( string $query_var, mixed $default_value = '' ): mixed


    1. $query_var (string, required): This is the name of the query variable you want to retrieve. WordPress query variables are pre-defined values that represent certain states or actions in a WordPress environment. Examples include 'p' for post ID, 'category_name' for category slug, 'tag' for tag slug, etc.

    2. $default_value (mixed, optional): This is the value that will be returned if the specified query variable $query_var is not set or found. The default value for this parameter is an empty string ''. You can set it to any value you prefer to be returned in the absence of the query variable.

    Return Value:

    • mixed: The function returns the contents of the specified query variable. The type of the returned value can vary depending on the content of the query variable. It could be a string, integer, array, etc.

    Example Usage:

    // Assume you want to retrieve the value of a custom query var 'my_var'
    $my_var_value = get_query_var('my_var', 'default_value');
    // Check if the variable has a value and use it
    if ($my_var_value != 'default_value') {
        echo 'Value of my_var: ' . $my_var_value;
    } else {
        echo 'my_var is not set in the query.';

    In this example, get_query_var is used to fetch the value of a custom query variable named 'my_var'. If 'my_var' is not set in the query, it returns 'default_value'. The function then checks if 'my_var' has a value other than the default, and if so, it prints the value. If 'my_var' is not set, it prints a message indicating that.

    This function is very useful for theme and plugin developers who need to work with different aspects of WordPress queries and need a reliable way to access query variables.

Leave an answer