Categories
How To

Making Plugins Filterable

I’m really bad at thsi since, generally, I don’t know why people would want to with the plugins I make. Which means I don’t do it. Which means I didn’t know how.

I have a plugin that records the IP address of users as they register and outputs it on the ‘show users’ page. It’s simple and it works.

Someone asked me if I could make it link to a place where he could see where the IP was from. Now my intent with the plugin was to list the IPs so I could spot serial sock puppets. But this use-case, I agreed, was valid. I just didn’t want to tie my plugin into one service or another. So I made it filterable.

As it happens, it was incredibly simple. This is filed under “Stuff I should have known years ago…”

Make The Output Filterable Make The Output Filterable

Originally I had the code outputting $theip and, in order to make it filterable, I wrapped that with this:

if ( has_filter('ripm_show_ip') ) {
    $theip = apply_filters('ripm_show_ip', $theip);
}

The whole function looks like this:

	public function columns($value, $column_name, $user_id) {
        if ( $column_name == 'signup_ip' ) {
            $ip = get_user_meta($user_id, 'signup_ip', true);
            if ($ip != ""){
                $theip = $ip;
				if ( has_filter('ripm_show_ip') ) {
					$theip = apply_filters('ripm_show_ip', $theip);
				}
                return $theip;
            } else {
                $theip = '<em>'.__('None Recorded', 'register-ip-multisite').'</em>';
                return $theip;
            }
        }
	    return $value;
	}

You’ll notice the has_filter() check is only on one possible output? That’s because I’m translating the output on the other one, which says “None Recorded” I could filter that, so people could change it to anything they want, but right now I think that’s a bit odd.

Top ↑

Filter The Output Filter The Output

To test this, I made a file /mu-plugins/register-ip-multisite.php and put the following inside:

function filter_ripm_show_ip($theip) {
    $theip = '<a href="https://duckduckgo.com/?q='.$theip.'" target="new">'.$theip.'</a>';
    return $theip;
}
add_filter('ripm_show_ip', 'filter_ripm_show_ip');

That made it a link. Simple.

Top ↑

Does It Work? Does It Work?

Of course!

Example of users screen with the IP showing as a link

I did not apply the filter to the output on the edit-users page, but if that turns out to be needed, I can.