How to execute conditional script when on new customize.php (Theme Customize) screen

Okay, first, let’s set things up properly, with a callback hooked into an appropriate action hook:

<?php
function wpse55227_enqueue_scripts() {
    // Enqueue code goes here
}
add_action( 'wp_head', 'wpse55227_enqueue_scripts' );
?>

We’ll put all of our code in to this callback.

The next step is to add our if ( ! is_admin() ) conditional wrapper:

<?php
function wpse55227_enqueue_scripts() {
    if ( ! is_admin() ) {
        // Enqueue code goes here
    }
}
add_action( 'wp_head', 'wpse55227_enqueue_scripts' );
?>

Now, let’s add in your original code:

<?php
function wpse55227_enqueue_scripts() {
    if ( ! is_admin() ) {
        if(!get_option('my_scripts_head')){
            remove_action('wp_head', 'wp_print_scripts');
            remove_action('wp_head', 'wp_print_head_scripts', 9);
            remove_action('wp_head', 'wp_enqueue_scripts', 1);
            add_action('wp_footer', 'wp_print_scripts', 5);
            add_action('wp_footer', 'wp_enqueue_scripts', 5);
            add_action('wp_footer', 'wp_print_head_scripts', 5);
        }
    }
}
add_action( 'wp_head', 'wpse55227_enqueue_scripts' );
?>

So, at this point, we should be back to where you were before. Now, let’s account for the Customizer. The easiest way is to check for the $wp_customize global being set:

<?php
function wpse55227_enqueue_scripts() {
    // Globalize
    global $wp_customize;
    // If $wp_customize is set, return
    if ( isset( $wp_customize ) ) {
        return;
    }

    if ( ! is_admin() ) {
        if(!get_option('my_scripts_head')){
            remove_action('wp_head', 'wp_print_scripts');
            remove_action('wp_head', 'wp_print_head_scripts', 9);
            remove_action('wp_head', 'wp_enqueue_scripts', 1);
            add_action('wp_footer', 'wp_print_scripts', 5);
            add_action('wp_footer', 'wp_enqueue_scripts', 5);
            add_action('wp_footer', 'wp_print_head_scripts', 5);
        }
    }
}
add_action( 'wp_head', 'wpse55227_enqueue_scripts' );
?>

By the way: out of curiosity, why are you moving all of the script enqueueing to the footer? I would imagine that has a very high likelihood of breaking things, and/or causing unintended consequences.

Leave a Comment