I’m trying hook the customizer_preview_init action in order to trigger live preview of the changes I’m making in the customizer. However, my first test is failing. I’m just trying to get an alert to fire inside the .js
Any ideas what I’m doing wrong?
//Add customizer.php to admin:
if ( is_admin() ) :
require_once( GENESIS_ADMIN_DIR . '/customizer.php' );
customizer.php:
function mytheme_customizer_live_preview()
{
wp_enqueue_script(
'mytheme-themecustomizer', //Give the script an ID
get_template_directory_uri().'/framework/admin/customizer.js',//Point to file
array( 'customize-preview' ), //Define dependencies
'', //Define a version (optional)
true //Put script in footer?
);
}
add_action( 'customize_preview_init', 'mytheme_customizer_live_preview' );
customizer.js
alert('customizer.js loaded!');
( function( $ ) {
alert('Customizer!');
//Do Stuff
} )( jQuery );
Update: It appears that my enqueue is failing. The customizer.js file is nowhere to be found in the dev tools resource panel.
I’ve verified that the footer.php does in fact have a wp_footer() call as expected. This is Genesis theme, perhaps some filter affecting the enqueue?
The issue in this case has to do with how I added the customize.php script. I was loading it inside an is_admin() check (see updated question above where I have included that code branch).
After reading Otto’s post, I realized that the customizer hook does not fire in this context.
I wrote a quick plugin to reproduce your problem with a nearly vanilla multisite/network install, running the plugin on a sub site with the TwentyForteen theme. It consists out of two files, both residing in the same directory:
plugin.php
andtheme-customizer.js
:Main plugin file:
JavaScript test file:
Above works like a charm 🙂
Hint: You can use
plugin_dir_path()
in themes as well.EDIT
After @toscho comment above and his link to his answer here, I decided to test one vs. the other hook. And surprise!!1! not,
customize_controls_enqueue_scripts
shoots earlier and from a look up in core seems to be much more reliable due to the fact that it’s not hidden in a massive Singleton/Poor-Mans-Namespace in some random method.Conclusion: Go with
customize_controls_enqueue_scripts
and forget aboutcustomize_preview_init
. The former btw runs exactly aftercustomize_controls_init
callbacks were triggered, so there’s less chance for interference of other code.