WooCommerce指定分类显示随机产品缩略图及多分类布局实现咨询
Woocommerce 动态热门分类区块实现方案
一、完整功能代码
将以下代码添加到站点当前主题的functions.php文件,或自定义代码插件中:
// 输出8个分类的随机产品区块 if( !function_exists('custom_hot_category_blocks') ) { function custom_hot_category_blocks() { // 在这里替换为你需要展示的8个产品分类的slug $target_categories = array( 'clothing', 'shoes', 'accessories', 'bags', 'electronics', 'home', 'beauty', 'sports' ); $img_size = 'shop_thumbnail'; // 可修改为shop_catalog/shop_single调整图片尺寸 $output = '<div class="hot-categories-wrap">'; foreach( $target_categories as $cat_slug ) { $category = get_term_by('slug', $cat_slug, 'product_cat'); if( !$category ) continue; // 跳过不存在的分类 // 查询该分类下3个随机产品 $random_products = get_posts( array( 'posts_per_page' => 3, 'post_type' => 'product', 'orderby' => 'rand', 'post_status' => 'publish', 'tax_query' => array( array( 'taxonomy' => 'product_cat', 'field' => 'slug', 'terms' => $cat_slug, ) ) ) ); if( empty($random_products) ) continue; // 跳过无产品的分类 // 单个分类区块输出 $output .= '<div class="category-block">'; // 分类标题+跳转链接 $output .= '<h3><a href="'.get_term_link($category).'">'.$category->name.'</a></h3>'; $output .= '<div class="category-thumbs">'; foreach( $random_products as $p ) { $product = wc_get_product($p->ID); if( !$product ) continue; $output .= '<a href="'.$product->get_permalink().'">'.$product->get_image($img_size).'</a>'; } $output .= '</div></div>'; } $output .= '</div>'; return $output; } add_shortcode('hot_category_blocks', 'custom_hot_category_blocks'); } // 将区块插入到指定页面 function insert_hot_blocks_to_page() { // 将381替换为你要展示该区块的页面ID,如需全局展示可删除该行判断 if( !is_page( 381 ) ) return; echo do_shortcode('[hot_category_blocks]'); } add_action('wp_footer', 'insert_hot_blocks_to_page', 50);
二、配置说明
- 请先将代码中
$target_categories数组的值替换为你实际要展示的8个产品分类的slug - 如需修改图片展示尺寸,可替换
$img_size的取值,可选值为shop_thumbnail(缩略图)、shop_catalog(列表页尺寸)、shop_single(详情页尺寸) - 如需调整区块展示位置,可修改
add_action的挂载钩子,除了wp_footer外,也可以替换为主题自定义的内容钩子,或者直接在页面编辑器中使用[hot_category_blocks]短代码手动插入
三、布局样式配置
将以下CSS代码添加到主题自定义CSS面板,即可实现每行4列的布局效果,已兼容移动端:
.hot-categories-wrap { display: grid; grid-template-columns: repeat(4, 1fr); gap: 20px; margin: 30px 0; } .category-block { border: 1px solid #f0f0f0; padding: 16px; border-radius: 8px; background: #fff; } .category-block h3 { margin: 0 0 15px; font-size: 16px; text-align: center; } .category-block h3 a { color: #333; text-decoration: none; } .category-thumbs { display: flex; flex-wrap: wrap; gap: 8px; justify-content: center; } .category-thumbs img { border-radius: 4px; } @media screen and (max-width: 768px) { .hot-categories-wrap { grid-template-columns: repeat(2, 1fr); gap: 15px; } }
你可以根据自己的站点设计风格调整颜色、间距、圆角等样式参数。
内容的提问来源于stack exchange,提问作者Zubir Ahmed
相关产品推荐
相关产品推荐

