search
HomeBackend DevelopmentPHP TutorialMerge 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();

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();

?>

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();

}

?>

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();

?>

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
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
What is the difference between unset() and session_destroy()?What is the difference between unset() and session_destroy()?May 04, 2025 am 12:19 AM

Thedifferencebetweenunset()andsession_destroy()isthatunset()clearsspecificsessionvariableswhilekeepingthesessionactive,whereassession_destroy()terminatestheentiresession.1)Useunset()toremovespecificsessionvariableswithoutaffectingthesession'soveralls

What is sticky sessions (session affinity) in the context of load balancing?What is sticky sessions (session affinity) in the context of load balancing?May 04, 2025 am 12:16 AM

Stickysessionsensureuserrequestsareroutedtothesameserverforsessiondataconsistency.1)SessionIdentificationassignsuserstoserversusingcookiesorURLmodifications.2)ConsistentRoutingdirectssubsequentrequeststothesameserver.3)LoadBalancingdistributesnewuser

What are the different session save handlers available in PHP?What are the different session save handlers available in PHP?May 04, 2025 am 12:14 AM

PHPoffersvarioussessionsavehandlers:1)Files:Default,simplebutmaybottleneckonhigh-trafficsites.2)Memcached:High-performance,idealforspeed-criticalapplications.3)Redis:SimilartoMemcached,withaddedpersistence.4)Databases:Offerscontrol,usefulforintegrati

What is a session in PHP, and why are they used?What is a session in PHP, and why are they used?May 04, 2025 am 12:12 AM

Session in PHP is a mechanism for saving user data on the server side to maintain state between multiple requests. Specifically, 1) the session is started by the session_start() function, and data is stored and read through the $_SESSION super global array; 2) the session data is stored in the server's temporary files by default, but can be optimized through database or memory storage; 3) the session can be used to realize user login status tracking and shopping cart management functions; 4) Pay attention to the secure transmission and performance optimization of the session to ensure the security and efficiency of the application.

Explain the lifecycle of a PHP session.Explain the lifecycle of a PHP session.May 04, 2025 am 12:04 AM

PHPsessionsstartwithsession_start(),whichgeneratesauniqueIDandcreatesaserverfile;theypersistacrossrequestsandcanbemanuallyendedwithsession_destroy().1)Sessionsbeginwhensession_start()iscalled,creatingauniqueIDandserverfile.2)Theycontinueasdataisloade

What is the difference between absolute and idle session timeouts?What is the difference between absolute and idle session timeouts?May 03, 2025 am 12:21 AM

Absolute session timeout starts at the time of session creation, while an idle session timeout starts at the time of user's no operation. Absolute session timeout is suitable for scenarios where strict control of the session life cycle is required, such as financial applications; idle session timeout is suitable for applications that want users to keep their session active for a long time, such as social media.

What steps would you take if sessions aren't working on your server?What steps would you take if sessions aren't working on your server?May 03, 2025 am 12:19 AM

The server session failure can be solved through the following steps: 1. Check the server configuration to ensure that the session is set correctly. 2. Verify client cookies, confirm that the browser supports it and send it correctly. 3. Check session storage services, such as Redis, to ensure that they are running normally. 4. Review the application code to ensure the correct session logic. Through these steps, conversation problems can be effectively diagnosed and repaired and user experience can be improved.

What is the significance of the session_start() function?What is the significance of the session_start() function?May 03, 2025 am 12:18 AM

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

See all articles

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

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools