How to handle cookies from a WordPress plugin on a cached page?

I’m attempting to write a plugin that can work with cookies on a WordPress site that uses page caching (why?).

I’ve been following this tutorial on Esanctuary.net. I’m trying to write to the error_log to see if the cookie logic is working, but for some reason, I’m not getting any logs from the esanctuary_sidebar_cookie function when using the wp_ajax hooks.

Read More

I’m also making use of cookie.js to handle the setting of the cookie.

Here is my plugin code:

<?php
/*
Plugin Name: Example
Plugin URI: 
Description: 
Version: 0.0.1
Author: 
Author URI: 
*/
class Example {

    // Constructor
    function __construct() {
        add_action( 'wp_enqueue_scripts', array( &$this, 'add_js' ) );
        add_action( 'wp_ajax_my_action', array( &$this, 'esanctuary_sidebar_cookie' ) );
        add_action( 'wp_ajax_nopriv_my_action', array( &$this, 'esanctuary_sidebar_cookie' ) );
    }

    // PHP4 Constructor
    function Example () {
        $this->__construct();
    }

    function add_js() {
        if( !wp_script_is( 'cookiejs', 'queue' ) ) {
            wp_enqueue_script( 'cookiejs', plugins_url( basename( __DIR__ ) . '/js/cookie.min.js' ), array( 'jquery' ) );
        }
        wp_enqueue_script( 'cookieset', plugins_url( basename( __DIR__ ) . '/js/cookie-set.js' ), array( 'jquery' ) );
    }

    function esanctuary_sidebar_cookie() {
        error_log( 'esanctuary' );

        // Check if a cookie has been set
        if ( isset($_COOKIE["edition"]) ) {

            // Get the value of that cookie
            $edition = $_COOKIE["edition"];

            // Determine which sidebar to show based on that cookie
            if ($edition == 'new-york') {
                error_log( 'New York' );
            }

            else if ($edition == 'miami') {
                error_log( 'Miami!' );
            }

        } else {
            error_log( 'No!' );
        }

    }

}

$iMobieLandingLogic = new Example;

Here is my JavaScript code:

jQuery( document ).ready(function() {
    if (cookie.enabled()) {
        cookie.set('edition', 'new-york');
        var allCookies = cookie.all();
        console.log( allCookies );
    } else {
    }

    var data = {
        action: 'my_action',
        whatever: 1234
    };

    jQuery.post(cookiesetdata.ajaxurl, data, function(response) {
    });
});

Related posts