Wordpress: multiple queries

Asked

Viewed 41 times

2

I am making queries to search posts according to different parameters of custom fields, but I would like the result of the 3 queries to be displayed together.

function query() {
        foreach ($values1 as $value1) {
            $arrays[0][] = array(
                'key' => 'my-value1',
                'value' => $value1,
                'compare' => 'LIKE'
            );
        }

        $arrays[1]['relation'] = 'OR';
        foreach ($values2 as $value2) {
            $arrays[0][] = array(
                'key' => 'my-value2',
                'value' => $value2,
                'compare' => 'LIKE'
            );
        }

    if(!is_null($sofwares)) {
        $arrays[2]['relation'] = 'OR';
        foreach ($values3 as $value3) {
            $arrays[0][] = array(
                'key' => 'my-value3',
                'value' => $value3,
                'compare' => 'LIKE'
            );
        }
    }
}

$args = array(
'category' => 'my-category',
'posts_per_page'  => 5
);
$args['meta_query'] = query(); //chamo a função para montar
$posts = get_posts($args);

How could I make all the results of this query come together, as if they were concatenated into a single group of posts to be shown in the loop. I tried to use arrays to make multiple queries, but it’s not working as expected, which would unite in the results all posts found in the 3 queries.

1 answer

2


You can use the function: array_merge() to join the found results, for example:

        $args1 = array(
            'category' => 'my-category',
            'posts_per_page'  => 5
            'key' => 'my-value1',
            'value' => $value1,
            'compare' => 'LIKE'
        );
        $args2 = array(
            'category' => 'my-category',
            'posts_per_page'  => 5
            'key' => 'my-value2',
            'value' => $value2,
            'compare' => 'LIKE'
        );
        $posts_args1 = get_posts( $args1 );
        $posts_args2 = get_posts( $args2 );
        // todos os resultados será armazenada nessa variável, depois é so percorrer ;)  
        $mergedposts = array_merge( $posts_args1, $posts_args2 );
  • 1

    That helped, thank you

  • 1

    perfect........

Browser other questions tagged

You are not signed in. Login or sign up in order to post.