WordPress多站点自定义主题报错:wp.customize is not a function
解决WordPress多站点中
wp.customize is not a function错误 这个错误的核心原因很明确:你的customizer.js脚本在加载时,既没有依赖WordPress定制器的核心脚本,还错误地使用了前台脚本加载钩子——导致脚本可能在定制器环境外被加载,就算在定制器里,核心的wp.customize对象还没准备好就执行了你的代码。
下面是具体的修复步骤:
1. 修正定制器脚本的加载钩子与依赖
打开你的customizer.php,找到加载custom-script的函数,把它从wp_enqueue_scripts(前台脚本钩子)替换成定制器专属钩子,并添加正确的依赖:
情况1:如果customizer.js用于定制器预览实时刷新(配合postMessage实现即时预览)
function wpdocs_scripts_method() { wp_enqueue_script( 'custom-script', get_stylesheet_directory_uri() . '/js/customizer.js', array( 'jquery', 'customize-preview' ), // 必须添加customize-preview依赖,确保wp.customize先加载 wp_get_theme()->get('Version'), // 用主题版本号作为缓存戳,比固定值更灵活 true ); } // 替换为定制器预览初始化钩子,只在定制器预览界面加载脚本 add_action( 'customize_preview_init', 'wpdocs_scripts_method' );
情况2:如果customizer.js用于定制器控件本身的交互(比如自定义控件的JS逻辑)
function wpdocs_scripts_method() { wp_enqueue_script( 'custom-script', get_stylesheet_directory_uri() . '/js/customizer.js', array( 'jquery', 'customize-controls' ), // 改用customize-controls依赖 wp_get_theme()->get('Version'), true ); } // 用控件加载钩子,只在定制器控件界面加载 add_action( 'customize_controls_enqueue_scripts', 'wpdocs_scripts_method' );
2. 在JS代码中增加安全检查
打开customizer.js,在使用wp.customize之前先检查它是否存在,避免意外场景下报错:
jQuery(document).ready(function($) { // 先确认wp.customize对象存在再执行逻辑 if (typeof wp.customize !== 'undefined') { // 这里放你的定制器逻辑,比如绑定postMessage刷新 wp.customize('banner_title', function(value) { value.bind(function(newVal) { // 替换成你页面上对应的元素选择器 $('.banner-title').text(newVal); }); }); wp.customize('banner_para', function(value) { value.bind(function(newVal) { $('.banner-para').html(newVal); }); }); // 其他定制器绑定逻辑... } });
3. 多站点环境额外检查
- 确保测试站点的主题是正确激活的,没有被多站点的网络设置限制
- 暂时禁用其他插件,排查是否有插件干扰了定制器脚本的加载
另外提个小问题:你的functions.php里注册mediaelement脚本时用了plugins_url,但这是主题文件,应该改用get_template_directory_uri(),避免路径错误:
wp_register_script('mediaelement', get_template_directory_uri() . '/wp-mediaelement.min.js', array('jquery'), '4.8.2', true);
内容的提问来源于stack exchange,提问作者Mat
相关产品推荐
相关产品推荐

