Module Development

Define a Custom Views Filter Plugin for Drupal 8, 9, and 10

Filter plugins provide the logic for determining what items to include in a view. They are the equivalent of a WHERE clause in an SQL statement. Filters can be exposed to the end user, allowing the viewer to enter a value, or select from a list of options, that are used to filter a list. For example, the options at the top of the Content list at /admin/content allow you to limit the list by content type.

Drupal's Views module provides filter plugins that can handle filtering for all core defined field types, as well as generic data types like numbers and strings. In situations where these filters don't meet your functional requirements, or you need a filter for a custom field, you may want to define a custom Views filter plugin. A common real-world scenario is defining a new filter plugin that extends an existing one and adds new possible values or options. For example, providing a relative date filter that allows a user to choose options like Last week or Last month.

In this tutorial we'll:

  • Learn how to create a Views filter plugin
  • Associate our new custom filter with data exposed to Views so it can be used
  • Learn how to use it in a view as an exposed filter

By the end of this tutorial you should know how to create a custom filter plugin and use it in Views.