$conf, $runtime; function_exists('chdir') AND chdir(APP_PATH); $r = 'mysql' == $conf['cache']['type'] ? website_set('runtime', $runtime) : cache_set('runtime', $runtime); } function runtime_truncate() { global $conf; 'mysql' == $conf['cache']['type'] ? website_set('runtime', '') : cache_delete('runtime'); } register_shutdown_function('runtime_save'); ?>wp query - How to combine two or more WP_Query?|Programmer puzzle solving
最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

wp query - How to combine two or more WP_Query?

matteradmin8PV0评论

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

Articles related to this article

Post a comment

comment list (0)

  1. No comments so far