skip to Main Content

I want to combine 2 arrays from WP_Query.

To call the 1 data, the code is like this:

$query = new WP_Query(array('post_type' => 'reply') );
 
        foreach ($query->posts as $p){
         
            echo 'ID :'.$p->ID."<br />rn";
        }

If using variable, just insert it into WP_Query parameters. Like this:

$args1 = array('post_type' => 'reply');
    $query = new WP_Query($args1);
 
        foreach ($query->posts as $p){
         
            echo 'ID :'.$p->ID."<br />rn";
        }

But my question is, I want to combine it with 'post_type' => 'topic'

for example the output for args1

'post_type' => 'reply':

ID :519
ID :517
ID :516
ID :515
ID :514
ID :500
ID :499
ID :485
ID :479
ID :478

and args2 for:

'post_type' => 'topic':

ID :498
ID :484
ID :483
ID :474

I want to combine both of them. I tried to array_merge() and array_combine() but the output is not what I expected. Any ideas to solve it?

Thank you in advance.

2

Answers


  1. Chosen as BEST ANSWER

    I found the solution, from this link: https://wordpress.stackexchange.com/questions/55519/can-i-merge-2-new-wp-queryvariable-s

    So, from what I learn. If you want to combine the array, you need to make another new WP_Query(). 1 WP_Query for your data topic, and 1 WP_Query for your data reply. And make another one for the result. The code look like this:

        $query1 = new WP_Query( array('post_type' => 'topic') );
        $query2 = new WP_Query( array('post_type' => 'reply') );
        $wp_query = new WP_Query();
        $wp_query->posts = array_merge($query1->posts, $query2->posts);
    
        foreach ($wp_query->posts as $p){
            echo 'ID :'.$p->ID."<br />rn";
        }
    

    Thank you for everyone that answer my question.


  2. You can have multiple post_types with an array, like this:

    $query = new WP_Query( array(
            'post_type' => array('reply', 'topic')
        ) );
    
    foreach ($query->posts as $p){     
        echo 'ID :'.$p->ID."<br />rn";
    }
    

    To see more details, please check this link.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search