Random WordPress Function

Learn about a new WordPress function every day!


Function Signature:

get_query_var

Function Description:

Retrieves the value of a query variable in the WP_Query class.

Function Examples:

⚠️ Examples below are generated with GPT-3 once every hour. Do not take them too seriously.
Consider them as some extra input in your learning process - reason about them. Will it work? What could fail?
// Example 1: Retrieve a custom query variable named 'category' from the URL
$category = get_query_var('category');
if($category){
    echo 'The category is: ' . $category;
} else {
    echo 'No category specified';
}
// Example 2: Get the value of a query variable 'author_id' and sanitize it before using
$author_id = get_query_var('author_id');
if($author_id){
    $sanitized_author_id = absint($author_id); // Sanitize the value as an integer
    echo 'The author ID is: ' . $sanitized_author_id;
} else {
    echo 'No author ID specified';
}
// Example 3: Check if a custom query variable 'search_query' exists and display search results accordingly
$search_query = get_query_var('search_query');
if($search_query){
    $search_results = new WP_Query(array(
        's' => $search_query // Use the search query to retrieve search results
    ));
    if($search_results->have_posts()){
        while($search_results->have_posts()){
            $search_results->the_post();
            the_title();
            echo '
'; } wp_reset_postdata(); } else { echo 'No results found for the search query: ' . $search_query; } } else { echo 'No search query specified'; }