I was recently tasked with adding the ability for writers to enter simple shortcodes in Drupal’s WYSIWYG editor. My first thought was, no problem! It’ll only take me a few minutes. Like with everything Drupal, nothing is that simple. The ease at which WordPress makes it for developers to create and build blows Drupal out of the water. Simple tasks like creating these shortcodes —
filters in Drupal speak—is a cinch using WordPress’s Shortcode API. So, how do you add custom shortcodes in Drupal?
Custom Shortcodes in Drupal 7
Build the Drupal Functionality
I started off with building a custom module that will hold my shortcode logic. Here’s the directory structure:
First, you need to tell Drupal about your module. In the
name = Custom Shortcodes
description = Sets up a custom filter that enables custom shortcodes.
core = 7.x
That’s it for that file. Next comes the
custom_shortcodes.module file. This is where all the magic happens:
That’s it for the module. Now, you’ll need to enable it through admin/modules or with Drush:
Once you’ve enabled the module, you’ll need to update the text formats so the Custom Shortcodes filter is enabled through admin/config/content/formats.
Now when you enter
[style:class_name]Content[/style] in Drupal’s WYSIWYG editor, the front-end output will look like this:
Wouldn’t it be nice to have a button on the editor to do this for you? I agree. But alas, haven’t figured out that part yet. Once I do, I’ll come back and update the post so you’ll know what I know. In the meantime, I’d love to hear your thoughts, suggestions or even a way to add that button, comment below!
Thanks to Matt Alexander for the regular expression!