Table of Contents
Define variables based on the main query
Example 1: Displaying posts from only one post type on category pages
Example 2: Main query combined with WP_Query and foreach to output multiple loops
Example 3: Two separate queries for two post types
Summary
Home Backend Development PHP Tutorial Merge WP_Query with main query

Merge WP_Query with main query

Aug 30, 2023 pm 07:57 PM
wp_query (wordpress) Main query (wordpress) Merge (code)

Merge WP_Query with main query

So far in this series, you have learned how to use WP_Query to create a custom query for use in a theme or plugin.

In most cases you will be using WP_Query with a whole new set of parameters that are separate from the parameters in the main query, but what if you want to include the main query in the parameters?

Examples of where you might want to do this include:

  • On category or category pages, only show posts from one post type
  • On category pages, display posts containing the current category and other categories or tags or taxonomy terms
  • On pages of post type, only show posts with specific metadata

I could go on and on, there are many opportunities to combine the main query with your own custom query.

I will demonstrate this with three examples: the first is a simple example with a loop; the second will use foreach to output multiple loops, one for each three post types; the third will output both post types on the category archive using two separate queries.

Define variables based on the main query

However, you are combining the main query with the WP_Query, you need to store the current query object arguments in a way that is easy to use in the WP_Query argument. The easiest way is to assign it to a variable.

Do this before defining the WP_Query parameter like this:

$mainquery = get_queried_object();
Copy after login

get_queried_object() The function returns the currently queried object, no matter what the object is. On a single post it will only return the post object, while on an archive it will return a category, tag, term object or any object related to the archive. It returns the ID of the query object.

You can then use this $mainquery variable in the WP_Query parameter. Now let's look at some examples.

Example 1: Displaying posts from only one post type on category pages

Suppose you have a custom post type added to your website and you have enabled categories for that custom post type. On the category archive for each category, you don't want to show posts: instead, you want to show posts of a new post type - let's call it product.

Your query might look like this:

<?php

$mainquery = get_queried_object();

$args = array (
    'category_name' => $mainquery->slug,
    'post_type' => 'product'
);

// Custom query.
$query = new WP_Query( $args );

// Check that we have query results.
if ( $query->have_posts() ) {

    // Start looping over the query results.
    while ( $query->have_posts() ) {

        $query->the_post();

        // Contents of the queried post results go here.

    }

}

// Restore original post data.
wp_reset_postdata();

?>
Copy after login

Since the category_name parameter I used above takes the category slug as a parameter, I need to add ->slug after the variable to output the category slug.

This gives you a query that fetches posts of product post type from the database with the current query category. You can use it on the category.php page template.

Note: You can also achieve this result by modifying the main query using the pre_get_posts hook and combining it with a conditional function to check the category archives.

Example 2: Main query combined with WP_Query and foreach to output multiple loops

The next example will output all posts from the current category page, but instead of displaying them all in one block, they will be separated by post type.

This means you can use CSS to categorize post types into blocks or columns on the page, or just separate them into different lists.

To do this you can use the following code:

<?php

$mainquery = get_queried_object();

$post_types = get_post_types();

foreach ( $post_types as $post_type ) {

    $args = array(
        'category_name' => $mainquery->slug,
        'post_type' => $post_type
    );

    // Custom query.
    $query = new WP_Query( $args );

    // Check that we have query results.
    if ( $query->have_posts() ) {

        // Start looping over the query results.
        while ( $query->have_posts() ) {

            $query->the_post();

            // Contents of the queried post results go here.

        }

    }

    // Restore original post data.
    wp_reset_postdata();

}

?>
Copy after login

This uses the $mainquery variable we used before, but it also adds a $post_types variable to store all the post types registered on the site, as well as a $post_type Variables store each individual post type in turn.

Example 3: Two separate queries for two post types

The last example is similar to the second example, but splits the post type into two separate queries, each with its own different loop. This gives you more control over what appears on each piece of content, so you can display your posts differently than your products, perhaps including featured images of your products or giving them a different layout.

Suppose your website registers the product post type and has categories enabled for it, and you are also writing a blog post with the same categories. On each category archive page, you want to display the ten most recent posts, and then you want to display a list of all products in the same category.

To do this, you can use code similar to:

<?php

$mainquery = get_queried_object();

// First query arguments for posts.
$args = array (
    'category_name' => $mainquery->slug,
    'post_type' => 'post',
    'posts_per_page' => '10'
);

// Custom query.
$query = new WP_Query( $args );

// Check that we have query results.
if ( $query->have_posts() ) {

    // Start looping over the query results.
    while ( $query->have_posts() ) {

        $query->the_post();

        // Contents of the queried post results go here.

    }

}

// Restore original post data.
wp_reset_postdata();

// Second query arguments for products.
$args = array (
    'category_name' => $mainquery->slug,
    'post_type' => 'product',
    'posts_per_page' => '-1'
);

// Custom query.
$query = new WP_Query( $args );

// Check that we have query results.
if ( $query->have_posts() ) {

    // Start looping over the query results.
    while ( $query->have_posts() ) {

        $query->the_post();

        // Contents of the queried post results go here.

    }

}

// Restore original post data.
wp_reset_postdata();

?>
Copy after login

You can then write each loop differently to output different data for each post type.

Summary

As you can see from the example above, using WP_Query not only allows you to create a completely custom query separate from the main query, but you can also merge the objects of the current query and create a more powerful query on the archive page .

The above example can also be done using other archive types: for category, author, date, etc. See if you can think of more possibilities!

The above is the detailed content of Merge WP_Query with main query. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

What are Enumerations (Enums) in PHP 8.1? What are Enumerations (Enums) in PHP 8.1? Apr 03, 2025 am 12:05 AM

The enumeration function in PHP8.1 enhances the clarity and type safety of the code by defining named constants. 1) Enumerations can be integers, strings or objects, improving code readability and type safety. 2) Enumeration is based on class and supports object-oriented features such as traversal and reflection. 3) Enumeration can be used for comparison and assignment to ensure type safety. 4) Enumeration supports adding methods to implement complex logic. 5) Strict type checking and error handling can avoid common errors. 6) Enumeration reduces magic value and improves maintainability, but pay attention to performance optimization.

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What is REST API design principles? What is REST API design principles? Apr 04, 2025 am 12:01 AM

RESTAPI design principles include resource definition, URI design, HTTP method usage, status code usage, version control, and HATEOAS. 1. Resources should be represented by nouns and maintained at a hierarchy. 2. HTTP methods should conform to their semantics, such as GET is used to obtain resources. 3. The status code should be used correctly, such as 404 means that the resource does not exist. 4. Version control can be implemented through URI or header. 5. HATEOAS boots client operations through links in response.

How do you handle exceptions effectively in PHP (try, catch, finally, throw)? How do you handle exceptions effectively in PHP (try, catch, finally, throw)? Apr 05, 2025 am 12:03 AM

In PHP, exception handling is achieved through the try, catch, finally, and throw keywords. 1) The try block surrounds the code that may throw exceptions; 2) The catch block handles exceptions; 3) Finally block ensures that the code is always executed; 4) throw is used to manually throw exceptions. These mechanisms help improve the robustness and maintainability of your code.

What are anonymous classes in PHP and when might you use them? What are anonymous classes in PHP and when might you use them? Apr 04, 2025 am 12:02 AM

The main function of anonymous classes in PHP is to create one-time objects. 1. Anonymous classes allow classes without names to be directly defined in the code, which is suitable for temporary requirements. 2. They can inherit classes or implement interfaces to increase flexibility. 3. Pay attention to performance and code readability when using it, and avoid repeatedly defining the same anonymous classes.

See all articles