如何实现带样式的WooCommerce产品画廊单页面嵌入短码?
修复WooCommerce产品画廊短码方案
一、修复自定义短码代码
你的现有代码存在几个关键问题:未正确获取短码传入的产品ID、缺少画廊所需的容器结构、未包含主产品图、直接echo导致输出异常。以下是修复后的完整代码:
function product_gallery_shortcode( $atts ) { // 检查WooCommerce核心函数是否存在 if ( ! function_exists( 'wc_get_gallery_image_html' ) || ! function_exists( 'wc_get_product' ) ) { return '<p>WooCommerce未启用</p>'; } // 处理短码属性,默认ID为空 $atts = shortcode_atts( array( 'id' => '', ), $atts ); // 验证产品ID有效性 if ( empty( $atts['id'] ) || ! is_numeric( $atts['id'] ) ) { return '<p>请传入有效的产品ID</p>'; } $product = wc_get_product( $atts['id'] ); if ( ! $product ) { return '<p>产品不存在</p>'; } $gallery_html = ''; $main_image_id = $product->get_image_id(); $attachment_ids = $product->get_gallery_image_ids(); // 构建WooCommerce画廊容器(保留原生样式类,确保样式正常加载) $gallery_html .= '<div class="woocommerce-product-gallery woocommerce-product-gallery--with-images images">'; // 添加主产品图 if ( $main_image_id ) { $gallery_html .= apply_filters( 'woocommerce_single_product_image_thumbnail_html', wc_get_gallery_image_html( $main_image_id, true ), $main_image_id ); } // 添加画廊缩略图 if ( ! empty( $attachment_ids ) ) { foreach ( $attachment_ids as $attachment_id ) { $gallery_html .= apply_filters( 'woocommerce_single_product_image_thumbnail_html', wc_get_gallery_image_html( $attachment_id ), $attachment_id ); } } $gallery_html .= '</div>'; // 短码必须返回HTML内容,不能直接echo,避免输出顺序混乱 return $gallery_html; } add_shortcode( 'product_gallery', 'product_gallery_shortcode' );
使用方法
在着陆页编辑器中插入短码,替换123为目标产品ID即可:
[product_gallery id="123"]
二、无需代码的插件推荐
如果不想自定义代码,可使用以下轻量插件实现需求:
- WooCommerce Product Gallery Slider:支持通过短码调用产品画廊,完全保留WooCommerce原生样式,可自定义画廊布局、缩略图数量等参数。
- Gallery for WooCommerce:专门针对产品画廊的增强插件,提供可视化短码生成工具,无需编码即可在任意页面插入带原生样式的产品画廊,支持响应式显示。
内容的提问来源于stack exchange,提问作者Joris vh
相关产品推荐
相关产品推荐

