# 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:** 3

<div class="post-metadata">

### Author: ![angus](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/angus/32/341715_2.png) [@angus](https://meta.discourse.org/u/angus)
#### Post date: [August 11, 2021, 5:51am UTC](https://meta.discourse.org/t/retrieve-topics-based-on-custom-field/199879/3 "2021-08-11T05:51:21Z")

</div>

The way to do this is

1. On the client: Add a topic query param using `api.addDiscoveryQueryParam`

2. On the server: Filter topic queries by the param using `add_custom_filter` in the `TopicQuery` class (see `lib/topic_query`)

The add\_custom\_filter callback will look a bit like this

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

```

---

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