WordPress & Cloudflare & that admin bar

When using Cloudflare or other external caching services, you really don’t want the admin bar to be cached (it happened today and would show itself to public users).

The filter below stops the admin bar from displaying on the public side of the WordPress site.

The nocache in the url query is used to bypass the proxy cache for this particular website (we also add it to all url’s if the user is logged in).

/**
* Show admin bar when logged or when nocache is being used on frontend site.
*/
add_filter('show_admin_bar', function()
{
  if (is_user_logged_in()) {
    if (is_admin()) {
       return true;
    }

    if (!isset($_REQUEST['nocache'])) {
      return false;
    }
  }

  return false;
});

Thie code below adds nocache query string to every URL, when the user is logged in. This helps bypass the proxy cache (with a page rule).

/**
 * Add no cache to generated links.
 *
 * @param string
 */
function add_nocache_to_url($url)
{
   if (is_user_logged_in()
      && stripos($url, 'nocache') === false) {
      $url .= stripos($url, '?') === false ? '?' : '&';
      $url .= 'nocache=1';
   }

   return $url;
}

/**
 * Only override when logged in.
 */
if (is_user_logged_in()) {
   add_filter('home_url', 'add_nocache_to_url', 99, 1);
   add_filter('post_link', 'add_nocache_to_url', 10, 1);
   add_filter('page_link', 'add_nocache_to_url', 10, 1);
   add_filter('post_type_link', 'add_nocache_to_url', 10, 1);
   add_filter('category_link', 'add_nocache_to_url', 11, 1);
   add_filter('tag_link', 'add_nocache_to_url', 10, 1);
   add_filter('author_link', 'add_nocache_to_url', 11, 1);
}