# Retrieve Topics based on custom field?

**URL:** https://meta.discourse.org/t/retrieve-topics-based-on-custom-field/199879
**Category:** Development
**Created:** [August 9, 2021, 9:39pm UTC](https://meta.discourse.org/t/retrieve-topics-based-on-custom-field/199879 "2021-08-09T21:39:27Z")
**Posts on this page:** 1
**Showing post:** 12

<div class="post-metadata">

### Author: ![JQ331](https://avatars.discourse-cdn.com/v4/letter/j/41988e/32.png) [@JQ331](https://meta.discourse.org/u/JQ331)
#### Post date: [August 13, 2021, 12:45pm UTC](https://meta.discourse.org/t/retrieve-topics-based-on-custom-field/199879/12 "2021-08-13T12:45:21Z")

</div>

UPDATE: I think I’ve got it (mostly) working (!). Now, this will show the “latest” topics matching the custom field value. (the #latest method was the closest one I could find that made sense in the `config/routes.rb` file).

It’s important that, in fact, **all topics** that have the relevant custom field `fun_level` value are loaded onto the page. Is there something else I need to do to make that happen?

* * *

Here’s the code for my own notes and in case helpful to others:

–I’ve created the custom field :fun\_level. Then:

**plugin.rb**

```plaintext
TopicQuery.add_custom_filter(:fun_level) do |topics, query|
  if query.options[:fun_level]
    topics.where("topics.id in (
      SELECT topic_id FROM topic_custom_fields
      WHERE (name = 'fun_level')
      AND value = '#{query.options[:fun_level]}'
    )")
  else
    topics
  end
end

```

**/connectors/my-plugin-outlet/fun-level.js.es6** (a javascript file that is activated when going to relevant page. So this javascript could be in an initializer or in a connector linking up to a plugin outlet. I like to use code that goes with a connector, so I’ll use setup component here):

```plaintext
const ajax = require('discourse/lib/ajax')

export default {
    setupComponent(args, component) {
      let parsedResultArray = []
      var endPoint = '/latest?fun_level=' + funLevel //funLevel = variable with value from the params   
      ajax(endPoint).then(function (result) {
            console.log('topic list result for topics matching that fun level = ')
            console.log(result.topic_list.topics)
            //parse results, and load them into parsedResultArray
            component.set('showTopics', parsedResultArray        
      })
   }
}

```

Now, the topics will be loaded into the `{{topic-list topics=showTopics}}` I have in the corresponding component, that’s put in the template through my-plugin-outlet.

This is a big step forward. **Thank you very much** , @angus.

---

_[View the full topic](https://meta.discourse.org/t/retrieve-topics-based-on-custom-field/199879)._
