WordPress锚点打开手风琴代码报错求助(418及语法错误)
解决WordPress锚点触发手风琴展开问题
需求
我是JavaScript和PHP新手,想在WordPress的Code Snippets插件中编写脚本,实现:访问带锚点的URL时,页面加载后自动滚动到对应ID的手风琴并将其展开。例如访问https://challengingbehavior.org/pyramid-model/overview/resources/#generalResources时,自动打开ID为generalResources的“General Resources”手风琴。
遇到的问题
- 第一段代码在激活Code Snippets插件片段时报错:
Could not create snippet. Request failed with status code 418 - 第二段代码放入
functions.php后,触发站点严重语法错误
环境信息
- 主机:Dreamhost
- WordPress版本:6.4.2
- PHP版本:8.3
错误代码示例
第一段代码
function add_this_script_footer(){ ?> <script> $(document).ready(function(){ var hash = window.location.hash; if(hash){ var element = $(hash); if(element.length){ element.trigger('click'); } } }); </script> <?php } add_action('wp_footer', 'add_this_script_footer'); ?>
第二段代码
//anchor link open accordion function anchor_open_accordion() { $(document).ready(function() { var hash = window.location.hash; if (hash){ var element = $(hash); if (element.length){ element.trigger('click'); } } }); } add_action('wp_footer', 'anchor_open_accordion');
问题原因
- 第二段代码核心错误:在PHP函数里直接写JavaScript代码,没有用
?>和<?php包裹JS输出,导致PHP解析时出现语法错误 - 第一段代码写法虽合规,但依赖jQuery且未处理滚动定位、重复触发问题,418错误大概率是插件临时请求异常,换正确写法即可解决
修正后的代码
直接复制到Code Snippets插件中创建新片段并激活即可:
function trigger_accordion_from_hash() { // 确保jQuery已加载(如果手风琴依赖jQuery) if ( ! wp_script_is( 'jquery', 'enqueued' ) ) { wp_enqueue_script( 'jquery' ); } ?> <script> // 等待DOM加载完成 document.addEventListener('DOMContentLoaded', function() { const hash = window.location.hash; if (hash) { // 获取锚点对应的手风琴触发元素 const accordionElement = document.querySelector(hash); if (accordionElement) { // 平滑滚动到目标元素 accordionElement.scrollIntoView({ behavior: 'smooth', block: 'start' }); // 判断手风琴是否已展开,避免重复触发 // 请将'is-open'替换为你手风琴展开时的实际类名 if (!accordionElement.classList.contains('is-open')) { accordionElement.click(); } } } }); </script> <?php } add_action('wp_footer', 'trigger_accordion_from_hash');
注意事项
- 如果手风琴不是通过点击触发展开,或者展开时的类名不是
is-open,需要根据实际情况修改代码中的判断逻辑 - 若手风琴完全不依赖jQuery,可以删除代码中关于jQuery加载的判断部分,不影响功能
内容的提问来源于stack exchange,提问作者PyramidModel
相关产品推荐
相关产品推荐

