WordPress自定义主题集成Isotope报错:Isotope is not defined
解决WordPress中Isotope未定义的错误
控制台出现Uncaught ReferenceError: Isotope is not defined,核心原因是脚本加载顺序错误和入队参数配置不当,导致main.js在Isotope库加载完成前就执行了。以下是具体修复步骤:
1. 修正functions.php中的脚本入队逻辑
原代码存在依赖关系错误、参数格式错误、版本号填写错误等问题,修改后的代码如下:
function amco_enqueue_assets() { // 加载样式表 wp_enqueue_style('fontawesome', get_template_directory_uri() . '/css/all.min.css', [], '6.4.0', 'all'); wp_enqueue_style('bootstrap', get_template_directory_uri() . '/css/bootstrap.min.css', [], '5.2.3', 'all'); wp_enqueue_style('custome-css', get_template_directory_uri() . '/css/style.css', [], filemtime(get_template_directory() . '/css/style.css'), 'all'); wp_enqueue_style('main-style', get_stylesheet_uri(), [], '1.0.0'); // 使用WordPress自带jQuery,避免版本冲突 wp_enqueue_script('jquery'); wp_enqueue_script('bootstrap', get_template_directory_uri() . '/js/bootstrap.min.js', ['jquery'], '5.2.3', true); // 修正Isotope版本号为实际对应版本(示例为3.0.6,可根据你的文件调整) wp_enqueue_script('isotope', get_template_directory_uri() . '/js/isotope.pkgd.js', ['jquery'], '3.0.6', true); wp_enqueue_script('lightbox-js', get_template_directory_uri() . '/js/lightbox.bundle.min.js', ['jquery'], '1.8.3', true); // 注册main-script时添加isotope为依赖,确保加载顺序正确 wp_register_script('main-script', get_template_directory_uri() . '/js/main.js', ['isotope'], filemtime(get_template_directory() . '/js/main.js'), true); wp_enqueue_script('main-script'); } add_action('wp_enqueue_scripts', 'amco_enqueue_assets');
2. 确保main.js在DOM加载完成后执行
Isotope需要操作DOM元素,必须等页面元素加载完成后再初始化,修改main.js:
// 等待DOM完全加载后执行初始化 document.addEventListener('DOMContentLoaded', function() { var gridElement = document.querySelector('#trade-list'); // 增加存在性检查,避免额外报错 if (gridElement && typeof Isotope !== 'undefined') { var grid = new Isotope(gridElement, { transitionDuration: "0.5s", }); // 绑定筛选按钮点击事件 var filterButtons = document.querySelectorAll(".filter-button-group button"); filterButtons.forEach(function (button) { button.addEventListener("click", function () { var filterValue = this.getAttribute("data-filter"); grid.arrange({ filter: filterValue }); }); }); } });
额外排查项
- 确认
isotope.pkgd.js文件路径正确,主题js文件夹下存在该文件且未损坏 - 打开浏览器开发者工具「Network」标签,刷新页面检查isotope.pkgd.js是否成功加载(状态码应为200)
- 临时禁用其他插件,排除插件冲突导致Isotope加载异常
内容的提问来源于stack exchange,提问作者Sarower Jahan
相关产品推荐
相关产品推荐

