Use ‘is_customize_preview’ and not ‘is_admin’ with Theme Customization API

Recently I came across a bug, and then another bug, when trying to solve a problem in the Theme Customization API. The site I was working on is using jQuery UI tabs, and when viewing the preview in the customzer, the script ended up looping and reloading the tabs over and over. This is a known bug (ticket 23225), so I decided I would add a condition to not load the jQuery UI script while in the customizer, using is_admin(). This did not work, so I decided to investigate further.

Turns out, is_admin() returns ‘false’ when in the customizer. Specifically, it returns ‘true’ until the page preview loads, at which point it returns ‘false’.

Happily, there is a new WP function that determines specifically when you are in the customizer. It is called ‘is_customize_preview()‘, and also returns a boolean. So a simple true == is_customize_preview() returns true in the customizer, and false everywhere else, including in other parts of the dashboard.

Here is the test and the results for those who are interested:

function debug_to_console( $data ) {
if ( is_array( $data ) || is_object( $data ) ) {
echo( "" );
} else {
echo( "" );

function test_is_admin() {
if( is_admin() ) {
debug_to_console( 'true is admin');
} else {
debug_to_console( 'false is admin');

add_action('wp_loaded', 'test_is_admin');

function test_is_customizer() {
if( true == is_customize_preview() ) {
debug_to_console( 'true is customize');
} elseif (false == is_customize_preview() ) {
debug_to_console( 'false is customize');

add_action('wp_loaded', 'test_is_customizer');

// front-end page: is_admin == false, is_customize_preview == false;
// admin page: is_admin == true, is_customize_preview == false;
// customizer: is_admin == false, is_customize_preview == true

Note: I was going to report this as a bug, but turns out it had been reported and is not considered a bug. Fair enough, just need to get the word out so developers don’t waste time on this small variance.

Post a comment

You may use the following HTML:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>