0

I'm working on programmatically searching content with the Search API module. Ideally I would like the ability to select which taxonomy term of a content type is being searched. For example, if I have a content type of 'restaurants' and three taxonomy terms representing the style of restaurants, lets say 'Italian', 'Chinese' and 'Fast Food'. I would then like the ability to search and get results of all the restaurants content entities associated with, lets say, just the Chinese taxonomy term.

Here is the code that I have so far:

$search_entry = $form_state->getValue('search');

$query = \Drupal\search_api\Entity\Index::load('forum_ct_search')->query();
$query->keys($search_entry);
$query->range(0, 5);

$result = $query->execute();
$items = $result->getResultItems();

This is working as far as I'm able to search the specific content type I'm interested. However I'm assuming there is a way to ask the Search API to just search by taxonomy terms. If it's possible, my best guess is that it is with the addCondition method, such as this:

$query->addCondition('type', ['article', 'snippet'], 'IN');

If this is the correct method for filtering by taxonomy term what are the correct parameters? If not how may I?

The other alternative would be to weed out the taxonomy terms from the results. This would work but it strikes me as cleaner to do it the other way.

Any ideas? Thanks!

(I'm running Drupal 8.6 with Search API 1.12)

0

Yes that's right to do addCondition here's a page with some examples https://www.drupal.org/docs/8/modules/search-api/developer-documentation/executing-a-search-in-code

So you'd just need to do the machine name of your indexed taxonomy field

$query->addCondition('my_indexed_field', $myvalue)
0

Hey thanks for the reply, because of it I pushed a bit harder and tried a few more things and I got it working. My primary mistake was that I wasn't using the taxonomy term id as the value, I kept using the term name instead. Here is the code that I got working.

$search_input => $form_state->getValue('search')    

$tax_field = 'field_taxonomy_name';    //Use Content field machine name.
$tax_term = 9;                         //Use Taxonomy Term ID (tid)

$query = Drupal\search_api\Entity\Index::load('forum_search_index')->query();
$query->setFulltextFields(['title', 'body']);
$query->keys($search_input);
$query->addCondition($tax_field, $tax_term);
$query->range(0, 50);

$result = $query->execute();
$result_items = $result->getResultItems();

Thanks again.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.