Module Development

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

Sort plugins are responsible for determining how the data in a list created with Views is sorted. Sort plugins are applied to fields. For example, a field might contain numbers and the sort plugin can handle putting the values into ascending or descending order. Typically, sort plugins work by adding to the ORDER BY clause of an SQL query.

The Views module provides sort plugins for all core field types. This includes handling for most primitive data types like strings and numbers. A typical use case for creating a custom sort plugin is extending an existing sort plugin with new conditions or custom sorting logic. For example, you might need to create an alphabetical title sort that excludes articles like a, an, and the. Or a sort based on combining the values in multiple fields.

In this tutorial we'll:

  • Learn how to create a custom Views sort plugin
  • Associate our custom sort plugin with a field exposed to Views
  • Use the sort plugin in a view to sort a list of Article nodes

By the end of this tutorial you should know how to create a custom sort plugin for the title field.