How to run code when cookie is added?

Question

So I have the code below, and its purpose is to prevent the Facebook for Woocommerce plugin from running the FB pixel until the necessary consent is given. It works to solve the problem in the sense that when a new page is loaded, if the cookie consent is given, it will load the Pixel.

My problem though is that the code does NOT run when someone hits the "accept cookies" button without refreshing the page. So is there any way to make the code below run when consent is given (ie, when the cookie is first added, without requiring you to refresh the page)?

add_filter( 'facebook_for_woocommerce_integration_pixel_enabled',
'checkStatisticsAccepted', 10, 1 );
function checkStatisticsAccepted() {
    if (isset($_COOKIE["CookieConsent"])) 
    { 
      switch ($_COOKIE["CookieConsent"])
      {
            case "-1":
                  //The user is not within a region that requires consent - all cookies are accepted
                  return true;
              
            default: //The user has given their consent 

                  //Read current user consent in encoded JavaScript format 
                  $valid_php_json = preg_replace('/s*:s*([a-zA-Z0-9_]+?)([}[,])/', ':"$1"$2', preg_replace('/([{[,])s*([a-zA-Z0-9_]+?):/', '$1"$2":', str_replace("'", '"',stripslashes($_COOKIE["CookieConsent"])))); 
                  $CookieConsent = json_decode($valid_php_json); 

                  if (filter_var($CookieConsent->statistics, FILTER_VALIDATE_BOOLEAN))
                  { 
                        return true;
                  } 
                  else 
                  { 
                        return false;
                 }
       }
    } 
    else 
        {
              return false;
        }
}
0
Johnny Walker 2 months 0 Answers 8 views 0

Leave an answer