Clearing The Filter Cache In Drupal

26th June 2009 - 3 minutes read time

Filters are used in Drupal to change the content of the text of a node when it is viewed. The important thing to note is that Drupal filters should never alter the actual content of the node itself. Instead, when a node is saved it stores the output of the filter in the cache_filter table and displays this content the next time the node is viewed. This is useful because it doesn't mess about with the original text, and it speeds up the displaying of the node by running the filters once, rather than every time the node is loaded.

However, there is one thing that you should watch out for when creating your own modules. If you are using any data from other tables in your filters then you will need to clear the cache when this data changes.

Lets take a real world example where we have a filter that allowed us to automatically filter taxonomy terms in a particular vocabulary within our node content and create links around them. When the node is saved we would have a cached version of the node that would contain a few links. The problem arises when we change any vocabulary information (like adding or deleting terms). The links would still be present in our content, even though the term has been removed.

Drupal provides a hook that allows you to catch any actions that occur upon the taxonomy, this is called hook_taxonomy() and has the following structure.

  1. function hook_taxonomy($op, $type, $array = array()){
  2. }

We only need to intercept any action with terms, so we first make sure that the type is a term. We have previously set a variable called mycustommodule_vocabulary, and we use this to filter by a single vocabulary, rather than everything, so the next step is to run a check for this. Finally, we run an SQL query that deletes everything from the cache_filter table, which effectively clears the filter cache.

  1. function mycustommodule_taxonomy($op, $type, $array = array()){
  2. switch($type){
  3. case 'term':
  4. $vid = variable_get("mycustommodule_vocabulary", '1');
  5. if ( $vid == $array['vid'] ) {
  6. // If a term has been altered within our selected vocab then delete the filter cache.
  7. db_query('DELETE FROM {cache_filter};');
  8. }
  9. break;
  10. }
  11. }

Note that this might be a little intensive on large sites with lots and lots of nodes, especially if you are doing a lot of term editing.

Add new comment

The content of this field is kept private and will not be shown publicly.