wp query - How to combine two or more WP_Query?

admin2025-06-02  1

I have two WP_Query like these:

Searching by s:

$query1 = new WP_Query([
  'post_type' => 'product',
  's' => $searchStr
]);

and searching by metabox:

$query2 = new WP_Query([
  'post_type' => 'product',
  'meta_query' => [
    [
      'key' => 'my_meta_key',
      'value' => $searchStr,
      'compare' => 'LIKE'
    ]
  ]
]);

How can I create a query to relate these two query by "OR", like:

`$query1 OR $query2" ?

I have two WP_Query like these:

Searching by s:

$query1 = new WP_Query([
  'post_type' => 'product',
  's' => $searchStr
]);

and searching by metabox:

$query2 = new WP_Query([
  'post_type' => 'product',
  'meta_query' => [
    [
      'key' => 'my_meta_key',
      'value' => $searchStr,
      'compare' => 'LIKE'
    ]
  ]
]);

How can I create a query to relate these two query by "OR", like:

`$query1 OR $query2" ?

Share Improve this question asked Mar 4, 2019 at 14:20 Lai32290Lai32290 3512 gold badges4 silver badges15 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

Hope this code may work for you.

$query1 = new WP_Query( array(
        'post_type' => 'product',
        's' => $searchStr
    ));

    $query2 = new WP_Query( array(
        'post_type' => 'product',
        'meta_query' => array(
            array(
               'key' => 'my_meta_key',
               'value' => $searchStr,
               'compare' => 'LIKE'
            )
         )
    ));

    $result = new WP_Query();
    $result->posts = array_unique( array_merge( $query1->posts, $query2->posts ), SORT_REGULAR );
    $result->post_count = count( $result->posts );
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1748842389a314178.html

最新回复(0)