Programming practices: Doing it right but wrong

The following exercise comes from Tom J Nowell, who addresses “the dark heart of the pluginPlugin A plugin is a piece of software containing a group of functions that can be added to a WordPress website. They can extend functionality or add new features to your WordPress websites. WordPress plugins are written in the PHP programming language and integrate seamlessly with WordPress. These can be free in the WordPress.org Plugin Directory https://wordpress.org/plugins/ or can be cost-based plugin from a third-party APIAPI An API or Application Programming Interface is a software intermediary that allows programs to interact with each other and share data in limited, clearly defined ways. and best programming practices.”

Install and activate the attached plugin.

super-rickroll.zip 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 filterFilter Filters are one of the two types of Hooks https://codex.wordpress.org/Plugin_API/Hooks. They provide a way for functions to modify data of other functions. They are the counterpart to Actions. Unlike Actions, filters are meant to work in an isolated manner, and should never have side effects such as affecting global variables and output. 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!

Last updated: