0

I want to write a query for my search page to show posts by two inputs. In my search form, i have to inputs, one is for category and the other is regular search term.

I want to show the posts that have the category keyword and search term. This is the code i have wrote so far :

$_place = $_GET['s'] != '' ? $_GET['s'] : '';
$_name = $_GET['n'] != '' ? $_GET['n'] : '';
$meta_query_args = array(
    'key'     => 'keywords',
    'value'   => $_name,
    'compare' => 'LIKE'
); 

$tax_query = array(
    'taxonomy'                      =>          'category', 
    'field'                         =>          'slug', 
    'terms'                         =>          $_place, 
    'operator'                      =>          'LIKE'
); 
$adSearchQuery = new WP_Query( array(
        'post_type'                     =>          'post',
        's'                             =>          $_name, 
        'meta_query'                    =>          $meta_query_args, 
        'tax_query'                     =>          $tax_query
    )   
);

$_place is the category. This code does not show any related result, in fact, most of the times it does not show anything.

So my main question is i want to show posts by similar terms ($_name) and similar categories ($_place).

By similar, i mean when i search the abc keyword, it shows the abcde or h abc d .

  • Define 'similar'. – Jacob Peattie Feb 8 '18 at 13:49
  • What is the $meta_query_args for? The current code searches for posts that have $_name in a custom field named keywords, in addition to matching the $_name search term ('s' argument) and being in the $_place category ('tax_query' arg). – Iceable Feb 8 '18 at 13:50
  • @jacob-peattie I edited the question with 'similar' definition. – Amirition Feb 8 '18 at 14:06
  • @iceable Yes you are right, $meta_query_args is extra but it still look for the posts with categories exactly the same as $_place. – Amirition Feb 8 '18 at 14:06
  • What you have is an "AND" query: 'keywords' LIKE $name AND search_term LIKE $name AND 'category' LIKE $place. What you want is a combination "AND" and "OR" query: ('keywords' LIKE $name OR search_term LIKE $name) AND 'category' LIKE $place. See this answer: wordpress.stackexchange.com/a/123193/129019 – Andy W Feb 8 '18 at 18:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.