Get access to variable from previous pageview, excluding ajax-calls

I want to generate a random string, and get it passed to the next pageview.

I currently have the following code:

  add_action('init', 'set_global_pixelcapival');
  function set_global_pixelcapival() {

      global $pixelcapival;
      $pixelcapival = pixelcapival();

      global $prev_pixelcapival;
      $prev_pixelcapival = '';

      if(isset($_COOKIE['pixelcapival'])) {
         $prev_pixelcapival = $_COOKIE['pixelcapival'];
      }

      setcookie('pixelcapival', $pixelcapival, time() + 1200, '/');
 }

I can now get access to $pixelcapival from the previous pageview by

global $prev_pixelcapival

But if any ajax-calls are being made in between, i guess the ajax-call triggers the init-action, and i don´t get the value i want. (The ajax-call is in this case made by a plugin, when clicking a submit-button)

Is there any easy way to prevent this? A hook that isn´t triggered by ajax calls?

Topic variables php hooks Wordpress

Category Web


I found out you could identify ajax requests by the following if-statement

if (defined('DOING_AJAX') && DOING_AJAX) 

So problem solved using

add_action('init', 'set_global_pixelcapival');
function set_global_pixelcapival() {
  if (defined('DOING_AJAX') && DOING_AJAX) { 
    
  } else {
    global $pixelcapival;
    $pixelcapival = pixelcapival();

    global $prev_pixelcapival;
    $prev_pixelcapival = '';

    if(isset($_COOKIE['pixelcapival'])) {
        $prev_pixelcapival = $_COOKIE['pixelcapival'];
    }
    setcookie('pixelcapival', $pixelcapival, time() + 1200, '/');
  }
}

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.