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

Woocommerce中添加账户图标至购物车旁:代码无效及PHP方案咨询

JavaScript代码无效的原因

你的代码完全没命中需求,主要问题有两个:

  1. 逻辑错误:你给#et-top-navigation父div添加了et-account-info类,但实际需要的是新增一个带该类的<a>标签,不是给父元素加类,方向完全错了。
  2. 执行时机问题:如果这段脚本在DOM加载完成前运行,document.getElementById("et-top-navigation")会返回null,根本无法执行后续操作。
更顺畅的PHP实现方式(针对Divi+WooCommerce)

从你的HTML类名来看,这是Divi主题的结构,推荐用主题自带钩子实现,无需修改模板:

方法1:利用Divi专属钩子

Divi提供了et_after_cart_info钩子,专门用于在购物车图标后插入内容,直接在主题functions.php中添加以下代码:

add_action( 'et_after_cart_info', 'add_account_link_after_cart' );
function add_account_link_after_cart() {
    // 仅在WooCommerce激活时执行
    if ( class_exists( 'WooCommerce' ) ) {
        // 获取我的账户页面链接
        $account_url = get_permalink( get_option( 'woocommerce_myaccount_page_id' ) );
        // 输出账户链接
        echo '<a href="' . esc_url( $account_url ) . '" class="et-account-info">';
        // 这里可以替换成你需要的图标或文本,比如Divi自带的用户图标
        echo '<span class="et-icon et-icon-user"></span>';
        echo '</a>';
    }
}

方法2:通用兜底方案

如果上述钩子无效,用wp_footer钩子配合JS确保DOM加载完成后插入:

add_action( 'wp_footer', 'insert_account_link_after_cart' );
function insert_account_link_after_cart() {
    if ( class_exists( 'WooCommerce' ) ) {
        $account_url = esc_url( get_permalink( get_option( 'woocommerce_myaccount_page_id' ) ) );
        ?>
        <script>
        document.addEventListener('DOMContentLoaded', function() {
            const cartLink = document.querySelector('.et-cart-info');
            if (cartLink) {
                const accountLink = document.createElement('a');
                accountLink.href = '<?php echo $account_url; ?>';
                accountLink.className = 'et-account-info';
                // 自定义图标或文本,比如换成"我的账户"
                accountLink.innerHTML = '<span class="et-icon et-icon-user"></span>';
                cartLink.insertAdjacentElement('afterend', accountLink);
            }
        });
        </script>
        <?php
    }
}

注意事项

  • 代码里的class_exists( 'WooCommerce' )是为了避免WooCommerce未激活时出错。
  • 图标/文本部分可以根据需求自由替换,比如把图标换成文字“我的账户”。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 10:01:57