wpCookies – Multi-value Cookies with JavaScript

One problem with cookies is, that they can only store numbers or text but no arrays or objects. This is something that the JavaScript class wpCookies can solve. Read on to know how wpCookies can manage all cookies for you.

wpCookies is part of the utils.js file and can be included with one

wp_enqueue_script( 'utils' );

Now you have a wpCookies class in JavaScript that helps with cookies.

wpCookies.getHash – Parse multi-value cookies in JavaScript

As it is almost impossible to store an object as a cookie value. This is what makes wpCookies so interesting:

var something = wpCookies.getHash( 'foo' );

// something can be a integer, string, array or object

The value that is returned can be a class, an array or other stuff. Read on and see how wpCookies.setHash handles that for us developer.

wpCookies.setHash – Store JavaScript arrays / objects in cookies

JavaScript can not store objects or arrays in one cookie. It always needs some transformation or a third snippet that helps out. The wpCookies class can do that and is included in the WordPress core:

var complexData = {
  'well': 'are objects complex?'
  'they': 'are just like php arrays.',
  130816: '5'
};

// wpCookies can store them all
wpCookies.setHash( 'complex', complexData );

So it is no longer a problem if you have primitive or complex values. The serialization of that is handled by wpCookies and you don’t need any other snippet or workaround to store arrays and objects in cookies.