Writing Drupal 7 input filters with hook_filter_info and DOMDocument

Lately I've been working on a new Drupal 7 theme for the university and while trying to configure the editor we ran into a few issues with adding classes to some dom elements. Primarily we don't want middle users to be able to add any classes or other attributes that we don't want them to use. We've got a set of pre-defined classes that they can use in their content. The wysiwyg_filter module pretty much takes care of enforcing that.

I also needed to do is to provide a filter to add some classes to a few different dom elements a user might include in a page. For instance, we want to add the img-responsive class to all images a middle user adds to the site. That way they are responsive by default, and Drupal's built in input filters makes it pretty simple to set everything up.

You start with implementing the hook_filter_info() hook with some information about your filter:

/**
 * Implements hook_filter_info()
 */
function mymodule_filter_info() {
  $filters = array();
  $filter['filter_image_classes'] = array(
    'title' => t('Adds default classes to images'),
    'process callback' => '_mymodule_images_process',
  );
  return $filters
}

After that we need to define the process callback for the filter.

function _mymodule_images_process($text, $filter) {
  if (!empty($text)) {
    $dom = new DOMDocument();
    $dom->loadHTML($text);
    $images = $dom->getElementsByTagName('img');
    foreach ($images as $image) {
      $classes = 'img-responsive other-class';
      $existing_classes = $image->getAttribute('class');
      if (!empty($existing_classes)) {
        $classes .= ' ' . $existing_classes;
      }
      $image->setAttribute('class', $classes);
    }
    $html = $dom->saveHTML();
    return $html;
  }
  return $text;
}

There you go, you're done. After you go to your input formats page and add the filter, clear the cache, you have a filter that automatically adds the img-responsive class to all images a middle user creates.

Add new comment

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.