I found that I need a must-use plugin.
First I created a folder: wp-content/mu-plugins
. Next I added the following code:
error_log('plugin filtering');
add_filter('option_active_plugins', function (array $plugins){
error_log(json_encode($plugins));
return $plugins;
});
It lists all my plugins before they are loaded.
So I can use a cookie to store user consent for different plugins and use this filter to turn off the plugins which don’t have user consent simply by unset($plugins[$noConsentPlugin]);
.
The only drawback that this solution requires a page reload after giving consent, while if we are not talking about plugins, but Javascript files, then a simple Javascript file loader would suffice without reloading the page. So it depends on how deeply for example Google Analytics is added to the page. As far as I know it can be as simple as loading a Javascript file or adding a pixel, which can be done with this latter solution.
Either way it takes around a day to implement a proper cookie consent plugin, so it is not that hard.