Skip to content

Instantly share code, notes, and snippets.

@nickdavis
Last active July 8, 2019 18:13
Show Gist options
  • Save nickdavis/6822613 to your computer and use it in GitHub Desktop.
Save nickdavis/6822613 to your computer and use it in GitHub Desktop.
Cookies with a cached WordPress website (on WP Engine)
<?php
// Call Ajax
add_action( 'wp_ajax_ajax_action', 'esanctuary_sidebar_cookie'); // ajax for logged in users
add_action( 'wp_ajax_nopriv_ajax_action', 'esanctuary_sidebar_cookie' ); // ajax for not logged in users
<?php
/**
* Load a different sidebar if a cookie is present via Ajax
* @author Nick Davis
* @link http://esanctuary.net/cookies-with-wordpress-caching
*/
function esanctuary_sidebar_cookie() {
// 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') {
dynamic_sidebar( 'sidebar-new-york' );
}
else if ($edition == 'miami') {
dynamic_sidebar( 'sidebar-miami' );
}
}
// If no cookie set just show regular sidebar
else {
dynamic_sidebar( 'sidebar' );
}
}
// Call Ajax
add_action( 'wp_ajax_ajax_action', 'esanctuary_sidebar_cookie'); // ajax for logged in users
add_action( 'wp_ajax_nopriv_ajax_action', 'esanctuary_sidebar_cookie' ); // ajax for not logged in users
<?php
/**
* Load a different sidebar if a cookie is present
* @author Nick Davis
* @link http://esanctuary.net/cookies-with-wordpress-caching
*/
function esanctuary_sidebar_cookie() {
// 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') {
dynamic_sidebar( 'sidebar-new-york' );
}
else if ($edition == 'miami') {
dynamic_sidebar( 'sidebar-miami' );
}
}
// If no cookie set just show regular sidebar
else {
dynamic_sidebar( 'sidebar' );
}
}
@thedamon
Copy link

Is there no javascript necessary to rerender the sidebar after load? would the page load with the default sidebar and then update to show the custom one based on the cookie call? I'm not entirely sure of the flow in the example here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment