I am new to Drupal and started learning hooks. I am trying to use hook_views_query_alter to show related content to user according to it's preferred tags.

function related_content_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
  if ($view->id() == 'filtered_content') {
    $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
    $getPrefTags = $user->get('field_user_tags')->getValue();
    if (empty($getPrefTags)) return;
    $prefTags = $getPrefTags[0]['target_id'];
    $nodeid = "node__field_tags.field_tags_target_id";

This function is getting value of user preferred tags from it's profile and then using addWhere() to alter the query. The problem is, this function is working fine if user inputs single tag but how can i do this if user inputs multiple tags. I tried using query->addWhere in loop to increase the value of $getPrefTags[0] but it didn't work. how can i achieve this.

  • Might be as simple as changing $prefTags to an array and the = to IN
    – Clive
    Jan 12 at 10:58

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.