Programming practices: Doing it right but wrong

The following exercise comes from Tom J Nowell, who addresses “the dark heart of the plugin API and best programming practices.”

Install and activate the attached plugin.

Download Zip – super-rickroll.zip

Expected Outcome Expected Outcome

When activated, your post content is replaced with a video you should know and love.

Top ↑

How to Fix How to Fix

There is absolutely no way to ‘fix’ this without deactivating the plugin or totally rewriting it’s behavior.

The problem is the code isn’t ‘wrong’ but it’s been written in a way to prevent it from ever being overwritten. Now it’s important to note that your content is not actually deleted or edited, it’s just filtered. Unlike most of our hacked code, this is crazy obvious what it does. If it had been base64’d and hidden, you’d know it’s bad. But as it looks right now, this isn’t bad code, is it? Well, the problem with the code is that there’s no way to turn off the filter without editing the file directly, as explained in the original the original Stack Exchange thread.

But that’s not true!

John Bloch came up with a solution:

<?php

function remove_filter_by_classname( $filter, $classname, $priority ) {
	global $wp_filter;
	$match = false;
	if( !empty( $wp_filter[$filter] ) && !empty( $wp_filter[$filter][$priority] ) ) {
		foreach( $wp_filter[$filter][$priority] as $added_filter ) {
			if( is_array( $added_filter['function'] ) && get_class( $added_filter['function'][0] ) === $classname ) {
				$match = $added_filter;
				break;
			}
		}
	}
	if( $match ) {
		remove_filter( $filter, $match['function'], $priority, $match['accepted_args'] );
	}
}

Still, this is something you shouldn’t be doing with your code!