You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WooCommerce单品页加载外部HTML实现点击弹出模态框问题咨询

错误原因分析

你遇到的Uncaught SyntaxError: expected expression, got '<'是用法错误导致的:

  • wp_enqueue_script()是专门用来加载JavaScript脚本的WordPress接口,不能直接加载HTML文件,浏览器会把HTML内容当做JS代码解析,碰到<开头的标签自然触发语法错误。
  • 额外注意:PHP函数名不能包含中划线-,你之前定义的popup-modal函数名本身就是语法错误,必须改成下划线popup_modal这类合法命名。

方案一:直接输出模态框HTML到单品页(推荐)

模态框内容量小的情况下,没必要单独存为外部HTML文件,直接和触发按钮一起输出即可,修改functions.php代码如下:

1. 修正资源入队逻辑

// 加载模态框依赖的JS和CSS
function my_enqueue_stuff() {
    if(is_singular( 'product' )) {
        // 加载模态框JS,指定依赖jQuery,加载到页脚避免阻塞
        wp_enqueue_script( 'modal-jquery-js', get_stylesheet_directory_uri() . '/js/modal-jquery.js', array('jquery'), '1.0', true );
        // 加载模态框CSS,路径对应你子主题css文件夹的实际路径
        wp_enqueue_style( 'modal-css', get_stylesheet_directory_uri() . '/css/modal.css', array(), '1.0' );
    }
}
add_action( 'wp_enqueue_scripts', 'my_enqueue_stuff' );

2. 输出触发按钮+模态框结构

add_action( 'woocommerce_before_add_to_cart_form', 'popup_modal_render', 3 );
function popup_modal_render() { 
    // 输出触发按钮
    echo '<a class="js-open-modal" href="#" data-modal-id="popup"> Click me </a>';
    // 直接输出模态框HTML,默认隐藏避免页面加载时闪现
    ?>
    <div id="popup" class="modal-box" style="display:none;">  
      <header>
        <a href="#" class="js-modal-close close">×</a>
        <h3>Modal Title</h3>
      </header>
      <div class="modal-body">
        <p>Modal Body</p>
      </div>
      <footer>
        <a href="#" class="js-modal-close">Close Button</a>
      </footer>
    </div>
    <?php
}

方案二:加载外部HTML文件的实现

如果你确实要把模态框HTML存为单独的文件,用PHP读取本地文件内容输出即可,不要用JS入队的方式:

add_action( 'woocommerce_before_add_to_cart_form', 'popup_modal_render', 3 );
function popup_modal_render() { 
    // 输出触发按钮
    echo '<a class="js-open-modal" href="#" data-modal-id="popup"> Click me </a>';
    // 读取本地HTML文件内容输出
    $modal_file_path = get_stylesheet_directory() . '/modal-box.html';
    if ( file_exists( $modal_file_path ) ) {
        echo file_get_contents( $modal_file_path );
    }
}

注意:需要手动给modal-box.html里的模态框根元素加style="display:none"默认隐藏样式。


内容的提问来源于stack exchange,提问作者PlainH2O

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 07:15:04