Skip to content

Instantly share code, notes, and snippets.

@AnadarProSvcs
Last active December 19, 2023 18:56
Show Gist options
  • Save AnadarProSvcs/c523abd44f80c4b8bfba563a81e40433 to your computer and use it in GitHub Desktop.
Save AnadarProSvcs/c523abd44f80c4b8bfba563a81e40433 to your computer and use it in GitHub Desktop.
WP_Query - An overview of the WP_Query in WordPress #wordpress

WordPress WP_Query Class Reference

Overview

WP_Query is a powerful class in WordPress used to query posts. It allows developers to specify a variety of parameters to retrieve posts, pages, custom post types, and more.

Key Properties

  • query: The query variables set in the new WP_Query instance.
  • query_vars: An array of query variables.
  • tax_query: The taxonomy query object.
  • meta_query: The meta query object.
  • date_query: The date query object.
  • post_count: The number of posts being displayed.
  • current_post: Index of the post currently being displayed.
  • in_the_loop: Whether the loop is currently being iterated.
  • post: The post object currently being iterated.
  • found_posts: The total number of posts found matching the current query parameters.
  • max_num_pages: The maximum number of pages of results.
  • is_single, is_preview, is_page, etc.: Booleans representing various WordPress conditional tags.

Common Methods

  • have_posts(): Determines whether current WordPress query has more posts to loop over.
  • the_post(): Iterates the post index in the loop.
  • get_posts(): Retrieves an array of posts based on set query variables.

Usage Example

$args = array(
    'post_type' => 'post',
    'posts_per_page' => 10
);
$query = new WP_Query($args);

if ($query->have_posts()) {
    while ($query->have_posts()) {
        $query->the_post();
        // Display or process the post.
    }
}
wp_reset_postdata();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment