Clearing The Filter Cache In Drupal

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.

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

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.

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

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.
CAPTCHA
5 + 4 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.