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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Working with Flash Session Data in Laravel Working with Flash Session Data in Laravel Mar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

PHP Logging: Best Practices for PHP Log Analysis PHP Logging: Best Practices for PHP Log Analysis Mar 10, 2025 pm 02:32 PM

PHP logging is essential for monitoring and debugging web applications, as well as capturing critical events, errors, and runtime behavior. It provides valuable insights into system performance, helps identify issues, and supports faster troubleshoot

cURL in PHP: How to Use the PHP cURL Extension in REST APIs cURL in PHP: How to Use the PHP cURL Extension in REST APIs Mar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

Simplified HTTP Response Mocking in Laravel Tests Simplified HTTP Response Mocking in Laravel Tests Mar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

12 Best PHP Chat Scripts on CodeCanyon 12 Best PHP Chat Scripts on CodeCanyon Mar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

Customizing/Extending Frameworks: How to add custom functionality. Customizing/Extending Frameworks: How to add custom functionality. Mar 28, 2025 pm 05:12 PM

The article discusses adding custom functionality to frameworks, focusing on understanding architecture, identifying extension points, and best practices for integration and debugging.

See all articles