Creating complex shortcodes in WordPress

I occasionally dabble in custom WordPress themes on my wife’s behalf and in furtherance of her vast eBook empire. As part of her current theme, she wanted some shortcodes to do neat things like having a multi-column section of a blog post. That way, she can write:

[columns]
[column]First column here![/column]
[column]Second column here![/column]
[/columns]

instead of the actual mess of HTML and CSS required to make such magic happen. Plus, if we ever decide to change the markup we’re using to generate columns, we can just change the implementation of the shortcode instead of going and updating a whole bunch of blog posts. Cool feature!

Defining a shortcode

In your theme’s functions.php, you need to do (at minimum) two things:

  1. Create a function that replaces the shortcode with its actual content.
  2. Register your shortcode with WordPress.

This part is straightforward. Say we wanted to create a [contentbox] shortcode to automatically wrapped its contents into an <aside>. That could look something like:

We could use it this way:

[contentbox align="right"]Here's a nice right-aligned piece of content![/contentbox]

When included in a post, that would become:

<aside class='content-box right'>Here's a nice right-aligned piece of content!</aside>

(CSS to make it actually look like a box and aligned right is left as an exercise for the reader.)

The evil that lies within

There’s a problem. WordPress has an ancient, vile, and notorious function in place which is designed to make users’ lives easier and developers’ lives miserable. This function is called wpautop and I hate it passionately.

The idea behind wpautop is simple: convert all double linebreaks into paragraph elements, and tack on <br> tags to whatever’s left. This lets an average user type text into the editor and have it converted to HTML even without using WordPress’ visual editor. The problem is that wpautop doesn’t know anything about shortcodes, so if our user splits our shortcode into several lines (such as the [columns] example at the top of this post), wpautop comes through and sprays <br> tags everywhere. Incidentally, <br> stands for “break”, which is exactly what wpautop is designed to do to nice complex shortcodes.

This problem has been known for ages – it was reported at least 9 years ago as of this writing, was still allegedly being discussed by WordPress devs 7 months ago, and there is no fix. Ridiculous.

Rescuing the shortcodes

There are at least four ways to deal with the problem of wpautop murdering our shortcode content:

Option 1: Change do_shortcode filter priority

While loading a page, WordPress executes a long list of “filters”, which are just functions that operate on the post’s content. wpautop is one such filter, as is do_shortcode. The latter is what ends up calling our own custom shortcode functions, replacing the shortcodes with actual content in the post. In WordPress core, wpautop runs at priority 10 and do_shortcode runs after that, at 11. So one way to thwart wpautop is to change do_shortcode‘s priority to 9, meaning our shortcodes will be resolved first and hopefully wpautop won’t mangle the output too badly.

This isn’t a great solution because it can potentially break all kinds of other themes or plugins (which might rely on WordPress’ default filter order) in subtle ways. Until today, I was using this approach for my wife’s site theme, but then we started switching her shopping cart to WooCommerce and discovered that my hack broke the text on the “proceed to checkout” button (because wpautop vomited a <br> randomly into the button text).

So if you take this route, expect occasional oddities with other plugins. This is not a well-behaved solution.

Option 2: Disable wpautop entirely

I love this option because I hate wpautop. However, this will likely break even more themes/plugins than option 1, and also users may not get the expected results if they’re composing posts in the text editor without using a sensible text parser like Markdown. Still, if you want to do it, just put these two lines into functions.php:

remove_filter( ‘the_content’, ‘wpautop’ );
remove_filter( ‘the_excerpt’, ‘wpautop’ );

Option 3: Disable wpautop on a post-by-post basis

You can install a plugin to disable wpautop only on certain posts–in our case, the ones with shortcodes on it.

I like how the plugin description explains its existence by saying “Back in the day, when the wpautop filter was really sucky…” What, you mean like yesterday?

Option 4: Hide the shortcodes behind a false bookcase

Like squirreling away guns or hiding Jews from the Nazis, this approach pretends that shortcodes don’t exist until after wpautop runs. It’s the most complicated, but it’s probably also the best because it lets wpautop commit whatever debauchery it wants on the post and then puts our precious shortcodes back in place unmolested. There are two steps:

  1. Register a filter before wpautop to search the post content for any shortcodes and replace them with random strings.
  2. Register a filter after wpautop but before do_shortcode to switch out the random strings for the original shortcode text.

Easier said than done, because finding complex shortcodes is no walk in the park. Fortunately, I’ve done the hard work for you!

When included in your functions.php file, the above code will:

  1. Search for any shortcodes in your post/page content.
  2. Once a shortcode opening tag is found, attempt to locate its corresponding closing tag.
  3. Replace the entire shortcode contents in the post with a random string.
  4. After wpautop has run, replace the random strings with the original shortcode markup.

After that, do_shortcode should run and evaluate your shortcodes normally.

Plex: Rename a TV Show Season

I’ve recently been working on digitizing our media collection using Plex. For the most part, the system works amazingly smoothly, provided you closely follow the naming conventions Plex expects, thus enabling it to find metadata about each file from the various online sources.

Problems arise when you want to add your own home media, or in my case, adding school media such as Math-U-See video lessons. Plex treats these as “TV shows” and it names TV show seasons using just the number, e.g. “Season 1”, “Season 2”, etc. This is not very helpful for identifying Math-U-See lessons, since they are named “Alpha”, “Beta”, etc.

Plex has a built-in editor for renaming the show itself, but inexplicably it does not provide an editor to change the name of a season. However, there is a way to do this. By adding an HTML input to the screen while editing a season, it turns out Plex saves the value and renames the season. Hooray! Just copy the following JavaScript and save it as a bookmarklet in your browser (in Chrome, go to the Bookmark Manager, Organize, Add Page, name it whatever you want, and paste the below code into the location box):

Then, in Plex, navigate to the season you want to rename, click the edit button, and click the bookmarklet. It will prompt you for a name. Enter whatever you like, click OK, then click Save Changes, and you’re done!

plex_rename_tv_show_season

Force MFC-8890DW to Keep Printing

Today we will be learning how to use a Magical Toner-Generating Device (MTGD) to enable your Brother black-and-white laser printer (specifically, model MFC-8890DW) to print even when it is out of toner! We’ll use this Weird Trick Invented by a Random Guy on the Internet! Printer Manufacturers Hate Him! But that’s okay, because The Feeling is Mutual!

(Full disclosure: I did not invent this trick. But I like to pretend that I did, because it makes me feel smarter and more nefarious.)

My Brother MFC-8890DW has been complaining of low toner for a while now, but I have been ignoring it because there is no appreciable difference in the documents it is printing. Then last week, right after printing a perfectly crisp page of text, the printer announced that I needed to Replace Toner and petulantly refused to print me more documents until I met its extortionate demands. However, based on my past experience with laser printers, I am under no illusions that they suddenly go from “prints just fine” to “completely out of toner”, and based on my experience with printer manufacturers, I am completely willing to believe that they will disable your printer and hold it hostage as a sort of scheme to force you into buying more printer supplies.

The general approach here is going to be to install a Magical Toner-Generating Device (MTGD). It works by absorbing the lies spewed forth by printer manufacturers and condensing them into a black powdery substances which can then be applied to paper the same as regular toner. Quality may vary, but so far I have found the results to be satisfactory. The device itself looks like this:

electrical_tape

Thus, we come to the nefarious directions for circumventing the printer’s extortion scheme. I like to think of this as the hostage (that’s me) escaping from the extortionist (that’s the printer), subduing it (after a brief scuffle), blindfolding it, putting it on the edge of a cliff, and holding a cattle prod to its back while shouting “Print, curse you! PRINT!” This process may violate the DMCA and/or other local laws, it may void your warranty, and it may result in an immense sensation of personal satisfaction. Use at your own risk.

  1. Open the front cover.
  2. Pull out the toner cartridge.
  3. On the right side of the cartridge, locate the little clear, round “observation window”.
  4. Apply the MTGD. That is to say, cover this window with black electrical tape.
  5. Put the cartridge back in and close the cover.

Here are two helpful illustrations of this complex technical procedure:

Toner cartridge: Before!

Toner cartridge: After!

In my case, this operation convinced the printer to merrily continue on its way, printing completely acceptable pages. (Since the printer claimed the toner was empty, and since we know a printer would never lie about its toner levels, I like to think it’s now using magic toner.)

I need to go do something else now, as I just heard a strange noise and the printer seems to have shifted position overnight, inching a little closer to my office chair. This won’t take long.