WooCommerce下拉分类导航悬停展示对应分类产品实现咨询
WooCommerce 下拉分类悬停展示对应产品实现方案
实现逻辑
- 给下拉导航的分类链接添加
data-cat-slug属性存储对应分类的别名(slug) - 新增WordPress AJAX接口,接收分类别名参数,返回对应分类最多8个产品的HTML结构
- 添加JS监听分类链接的悬停事件,触发时调用AJAX接口拉取产品数据,渲染到指定展示区域
- 调整CSS样式适配产品展示区域的排版
注意:以下代码均为WordPress + WooCommerce 环境下适用,需要将对应PHP代码放到当前激活主题的
functions.php文件中,CSS和JS代码可根据实际场景放到主题对应资源文件或自定义代码区块中。
1. 调整下拉导航代码
修改原HTML结构,新增产品展示容器,给分类链接加自定义属性:
<html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> .dropbtn { background-color: #04AA6D; color: white; padding: 16px; font-size: 16px; border: none; } .dropdown { position: relative; display: inline-block; } .dropdown-content { display: none; position: absolute; background-color: #f1f1f1; min-width: 160px; box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2); z-index: 1; } .dropdown-content a { color: black; padding: 12px 16px; text-decoration: none; display: block; } .dropdown-content a:hover {background-color: #ddd;} .dropdown:hover .dropdown-content {display: block;} .dropdown:hover .dropbtn {background-color: #3e8e41;} /* 新增产品展示区域样式 */ .product-show-area { display: none; position: absolute; left: 160px; top: 0; background: #fff; min-width: 300px; padding: 15px; box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2); z-index: 2; } .product-show-area ul { list-style: none; margin: 0; padding: 0; } .product-show-area li { margin-bottom: 15px; display: flex; gap: 10px; align-items: flex-start; } </style> <!-- 输出AJAX请求地址到前端 --> <script> const ajaxUrl = '<?php echo admin_url('admin-ajax.php'); ?>'; </script> </head> <body> <h2>Hoverable Dropdown</h2> <p>Move the mouse over the button to open the dropdown menu.</p> <div class="dropdown"> <button class="dropbtn">产品分类</button> <div class="dropdown-content"> <!-- 每个分类链接添加data-cat-slug存储对应分类的slug --> <a href="#" data-cat-slug="computers">Computers</a> <a href="#" data-cat-slug="televisions">Televisions</a> <a href="#" data-cat-slug="phones">Phones</a> </div> <!-- 产品展示容器 --> <div class="product-show-area"> <div class="product-list"></div> </div> </div> </body> </html>
2. 新增AJAX接口处理代码(放到主题functions.php)
接收前端传的分类slug,查询对应产品返回HTML:
// 处理已登录用户AJAX请求 add_action('wp_ajax_get_category_products', 'get_category_products_callback'); // 处理游客AJAX请求 add_action('wp_ajax_nopriv_get_category_products', 'get_category_products_callback'); function get_category_products_callback() { // 校验参数 if (!isset($_POST['cat_slug']) || empty($_POST['cat_slug'])) { wp_send_json_error('分类参数错误'); } $cat_slug = sanitize_text_field($_POST['cat_slug']); $wc_query = new WP_Query( array( 'post_type' => 'product', 'post_status' => 'publish', 'posts_per_page' => 8, // 限制最多返回8个产品 'tax_query' => array( array( 'taxonomy' => 'product_cat', 'field' => 'slug', 'terms' => $cat_slug, 'operator' => 'IN', ) ) ) ); ob_start(); if ($wc_query->have_posts()) : ?> <ul> <?php while ($wc_query->have_posts()) : $wc_query->the_post(); $product = wc_get_product(); ?> <li> <?php if (has_post_thumbnail()) : ?> <a href="<?php the_permalink(); ?>"> <?php the_post_thumbnail('thumbnail', ['style' => 'width:60px;height:60px;object-fit:cover;']); ?> </a> <?php endif; ?> <div> <h3 style="font-size:14px;margin:0 0 5px 0;"> <a href="<?php the_permalink(); ?>" style="color:#333;text-decoration:none;"><?php the_title(); ?></a> </h3> <p style="font-size:12px;margin:0;color:#666;"><?php echo wp_trim_words(get_the_excerpt(), 8); ?></p> <p style="font-size:14px;margin:5px 0 0 0;color:#04AA6D;"><?php echo $product->get_price_html(); ?></p> </div> </li> <?php endwhile; ?> </ul> <?php wp_reset_postdata(); else: ?> <p style="margin:0;color:#999;">暂无相关产品</p> <?php endif; $html = ob_get_clean(); wp_send_json_success($html); }
3. 新增悬停事件监听JS代码(放到页面底部或自定义JS文件)
document.addEventListener('DOMContentLoaded', function() { const catLinks = document.querySelectorAll('.dropdown-content a[data-cat-slug]'); const productArea = document.querySelector('.product-show-area'); const productListWrap = productArea.querySelector('.product-list'); let hideTimer = null; catLinks.forEach(link => { // 悬停分类触发产品查询 link.addEventListener('mouseenter', function() { clearTimeout(hideTimer); const catSlug = this.dataset.catSlug; productArea.style.display = 'block'; productListWrap.innerHTML = '<p style="margin:0;text-align:center;">加载中...</p>'; // 发送AJAX请求 fetch(ajaxUrl, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, body: `action=get_category_products&cat_slug=${catSlug}` }) .then(res => res.json()) .then(res => { if (res.success) { productListWrap.innerHTML = res.data; } else { productListWrap.innerHTML = `<p style="margin:0;color:red;">${res.data}</p>`; } }) .catch(err => { productListWrap.innerHTML = '<p style="margin:0;color:red;">加载失败,请刷新重试</p>'; }); }); // 移出分类延迟隐藏产品区,避免鼠标移动时闪烁 link.addEventListener('mouseleave', function() { hideTimer = setTimeout(() => { productArea.style.display = 'none'; }, 300); }); }); // 移入产品区取消隐藏,方便用户点击产品 productArea.addEventListener('mouseenter', function() { clearTimeout(hideTimer); }); productArea.addEventListener('mouseleave', function() { hideTimer = setTimeout(() => { productArea.style.display = 'none'; }, 300); }); });
内容的提问来源于stack exchange,提问作者SavPhill
相关产品推荐
相关产品推荐

