Enabling or disabling functionality based on Consent and Cookies

You are here:

Every functionality that is not essential should be disabled on the first landing. After the user agreed to your terms and gave explicit consent you can start enabling other stuff like tracking, advertising, mailing forms, etc…

How do I do that?

We have a couple helper functions for this.
They are has_consent( $consent_id ) and is_allowed_cookie( $cookie_name ).
Both functions are available in PHP and JavaScript.

You should wrap all code that creates cookies with is_allowed_cookie( $cookie_name ) and only load that piece of code if true. Something like this:

if ( is_allowed_cookie( 'my-cookie' ) {
  // Run my code and set the cookie.
}

In some cases, you need to check for both. Like Google Analytics for instance. The code below should be added to your theme functions.php and is assuming you registered an analytics consent and _ga as one of the cookies used.

add_action( 'wp_head', 'my_google_opt_out' );
function my_google_opt_out() {
  if ( ! is_allowed_cookie( '_ga' ) ) {
    ?>
    <script>
      window['ga-disable-UA-XXXXXXXX-X'] = true; // Don't forget to replace X for your actual UA numbers.
    </script>
    <?php
  }
}

The same functions are available in JavaScript for people that are using Caching plugins.

If you are running the above through JavaScript, you should be doing something like

if ( ! is_allowed_cookie( '_ga' ) ) {
  window['ga-disable-UA-XXXXXXXX-X'] = true; // Don't forget to replace X for your actual UA numbers.
}

You can read more about these functions at Functions & Shortcodes