Skip to content

Instantly share code, notes, and snippets.

@wkw
Last active April 5, 2024 08:26
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save wkw/6fc5aeb598ec0c1aa151 to your computer and use it in GitHub Desktop.
Save wkw/6fc5aeb598ec0c1aa151 to your computer and use it in GitHub Desktop.
WordPress functions to selectively disable WPEngine site caching temporarily.

Controlled WPEngine Cache Busting

This technique was used to control WPEngine's caching by making WPE think there was a WordPress CMS user logged in by setting a fake cookie.

This code was developed to display site-wide dynamic content when a user authenticated against an external (non-WordPress) service.

N.B.: this worked as of 10/2015, but WPE may make infratructure changes which break the technique.

Usage

When you need to disable caching, call maybe_set_user_cookie(). This function must be called on every page load until you no longer need to disable caching. To stop the caching and remove the fake cookie, call remove_user_cookie().

Typical usage would be to set the cookie just before you need it and continue to set it until caching can be enabled again for the current user.

<?php
/**
* set a fake logged-in user cookie to break out of
* wpe's caching as needed. Is only set if no other
* CMS logged-in-user cookie has been set already.
*
* @return boolean true if new cookie set. false otherwise
*/
function maybe_set_user_cookie() {
$cookie_was_set = false;
if ( false === ($cook = has_logged_in_user_cookie()) ) {
$expire = time()+3600; # modify expiration time to suit your needs
set_fake_user_logged_in_cookie($expire);
$cookie_was_set = true;
}
return $cookie_was_set;
}
# unset fake CMS user cookie
function remove_user_cookie() {
$expired = time()-3600;
set_fake_user_logged_in_cookie($expired);
}
function set_fake_user_logged_in_cookie($expire=0) {
$fake_user = '_fake_user_';
$cookie = 'wordpress_logged_in_' . md5($fake_user);
$value = md5($fake_user);
setcookie($cookie, $value, $expire, '/');
}
# determine if logged-in cookie is already set
function has_logged_in_user_cookie() {
$patt = 'wordpress_logged_in_';
foreach($_COOKIE as $cook => $val) {
if( 0 === strpos($cook, $patt) ) {
return $cook;
}
}
return FALSE;
}
@corpconv
Copy link

Still working as of today.

@smhaziqali
Copy link

Where to add this code?

@corpconv
Copy link

@gkarmas
Copy link

gkarmas commented Nov 14, 2022

not working anymore

@michael-sumner
Copy link

not working

@wkw
Copy link
Author

wkw commented Nov 16, 2022

Sorry about it not working. If I get time, I'll look into it.

@jakubmikita
Copy link

Still works, but the cookie name has to be dynamic. Do something like $fake_user = '_fake_user_' . time(); in line 30 and they won't exclude that cookie

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