📜  WP_Query - PHP (1)

📅  最后修改于: 2023-12-03 15:21:15.473000             🧑  作者: Mango

WP_Query - PHP

WP_Query is a powerful object-oriented way to query the WordPress database. This class is used in WordPress to get a collection of posts, pages, or custom post types that match certain criteria. With WP_Query, you can query for posts by category, tag, custom fields, date, author, and more.

This class provides a more flexible and customizable way of querying for posts than the default WordPress query class, and it can be used in your themes or plugins to display custom content.

Getting Started

To create a new WP_Query, start by creating a new instance of the class:

$query = new WP_Query( array( 'post_type' => 'post' ) );

Here, we’re creating a new query to get all posts from the ‘post’ post type.

Query Parameters

The WP_Query class takes an array of query parameters as its argument. In this array, you can specify the following parameters:

  • post_type: The post type (or types) to query.
  • category_name, cat: Retrieve posts by category name or ID.
  • tag: Retrieve posts by tag name or ID.
  • orderby: Order the results by any specific field (e.g. ‘date’).
  • order: The direction in which to order the results (ASC or DESC).
  • meta_key: The name of the meta field to use for ordering.
  • meta_value: The value of the meta field to use for ordering.
  • author: Retrieve posts by an author.
  • date_query: Restrict posts to a specific date range.
  • posts_per_page: How many posts to display per page.
  • offset: Number of posts to offset by.
  • paged: Page number of the query.
  • ignore_sticky_posts: Ignore sticky posts in the query.

Here is an example of a more complex query:

$args = array(
    'post_type' => 'portfolio',
    'tax_query' => array(
        array(
            'taxonomy' => 'category',
            'field'    => 'slug',
            'terms'    => 'photography',
        ),
    ),
    'meta_query' => array(
        array(
            'key' => 'featured',
            'value' => 'yes',
        ),
    ),
);
$query = new WP_Query( $args );

This query will retrieve all posts from the ‘portfolio’ post type that have the ‘photography’ category and are marked as ‘featured’.

The Loop

Once you have created a WP_Query, you can loop through the results using the have_posts() method and the_post() method:

if ( $query->have_posts() ) {
    while ( $query->have_posts() ) {
        $query->the_post();
        // Display post content here
    }
} else {
    // No Posts Found
}
Conclusion

WP_Query is a powerful tool that can be used to create custom queries for posts, pages, and custom post types. With its many query parameters, you can retrieve specific posts based on their category, tag, author, date, and more. If you need to display custom content in your themes or plugins, WP_Query is an essential tool to have in your toolkit.