Skip to content

Instantly share code, notes, and snippets.

@tzkmx
Forked from carlodaniele/plugin-filter.php
Last active July 11, 2020 14:25
Show Gist options
  • Save tzkmx/f4aa39f7f06a3d4c41fce7b19207d699 to your computer and use it in GitHub Desktop.
Save tzkmx/f4aa39f7f06a3d4c41fce7b19207d699 to your computer and use it in GitHub Desktop.
A Must-use plugin to filter active plugins in on a per-page basis.
<?php
add_filter( 'option_active_plugins', 'test_blacklist_unneeded_plugins', 40 );
function test_blacklist_unneeded_plugins( $plugins ) {
// We don't apply blacklisting to logged in users to prevent plugin deactivation
if( isset( $_SERVER['HTTP_COOKIE'] ) && is_user_logged_muplugin() ) {
return $plugins;
}
// returns the path of the request URI without the query string
// see http://php.net/manual/en/function.parse-url.php
// and http://php.net/manual/en/reserved.variables.server.php
// and http://php.net/manual/en/url.constants.php
$request_uri = parse_url( $_SERVER['REQUEST_URI'], PHP_URL_PATH );
$query = $_SERVER['QUERY_STRING'];
$is_admin = matchesAt( $request_uri, '/wp-admin/' );
$is_homepage = ('/' === $request_uri) && (strpos( $query, 'preview' ) == false);
$homepage_blacklisted_plugins = [
'akismet',
'amp',
'facebook-comments-plugin',
];
$single_post_blacklisted_plugins = [
'layered-popups',
];
if($is_homepage) {
return filter_array( $plugins, $homepage_blacklisted_plugins );
} elseif( !$is_admin ) {
return filter_array( $plugins, $single_post_blacklisted_plugins );
}
return $plugins;
}
function matchesAt( $tested_string, $match_lookup, $position = 0) {
return $position === strpos( $tested_string, $match_lookup );
}
function filter_array( $input_array, $blacklist_array ) {
return array_values( array_filter( $input_array, function( $input_value ) use ( $blacklist_array ) {
return empty( array_filter( $blacklist_array, function( $blacklisted_item ) use ( $input_value ) {
return matchesAt( $input_value, $blacklisted_item );
}) );
}) );
}
function is_user_logged_muplugin() {
$cookies_regex = '/' .
'wordpress_sec_(?P<hashsec>[0-9a-f]+)=(?P<usersec>[0-9a-z_.\-@]+)' .
'.*' .
'wordpress_logged_in_(?P<hashlog>[0-9a-f]+)=(?P<userlog>[0-9a-z_.\-@]+)' .
'|' .
'wordpress_logged_in_\k{hashlog}=\k{userlog}' .
'.*' .
'wordpress_sec_\k{hashsec}=\k{usersec}' .
'/';
if( preg_match($cookies_regex, $_SERVER['HTTP_COOKIE'], $cookies_user) ) {
if( $cookies_user['hashsec'] === $cookies_user['hashlog'] &&
$cookies_user['usersec'] === $cookies_user['userlog'] ) {
return true;
}
}
}
@tzkmx
Copy link
Author

tzkmx commented Nov 13, 2017

I've added in revision 3 a function to check if user is logged in with secure cookies to don't blacklist any plugin because it causes deactivation on some requests. Also the preview of unpublished posts could cause shortcodes and other features being unavailable even on frontend.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment