get_queried_object

Home » Functions » get_queried_object

Function Name: get_queried_object

Explanation: The get_queried_object function is a powerful WordPress function that retrieves the currently queried object from the global $wp_query object. It is commonly used in WordPress template files, especially in custom page templates or archive templates, to access information about the current object being queried.

This function returns the object representing the current queried entity, such as a post, page, custom post type, category, tag, or taxonomy term. It allows developers to access various properties and data associated with the queried object, such as the ID, title, content, metadata, and more.

Usage Example: Let’s say we have a custom page template that displays information about the current post being queried. We can utilize the get_queried_object function to retrieve the post object and then access its properties to display relevant information on the page.

<?php
// Check if the current object is a post
if (is_single()) {
    $queried_object = get_queried_object(); // Get the post object
    if ($queried_object) {
        // Display the post title
        echo '<h1>' . $queried_object->post_title . '</h1>';

        // Display the post content
        echo '<div>' . $queried_object->post_content . '</div>';

        // ... Additional customizations or data retrieval
    }
}
?>

In the above example, we first check if the current object being queried is a single post using the is_single function. If it is, we then use get_queried_object to retrieve the post object and store it in the $queried_object variable. We can then access properties such as post_title and post_content to display the respective data on the page.

By using the get_queried_object function, developers can create dynamic and personalized templates that fetch and display specific information based on the currently queried object, enhancing the overall user experience.

Learn More on WordPress.org

WordPress snippets using the get_queried_object function

Register an account to save your snippets or go Pro to get more features.