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

如何开发自定义插件实现WooCommerce商品图片在页面展示

WooCommerce单商品图片展示插件实现方案

你原有代码的问题是直接调用了WordPress默认的gallery短代码,读取的是当前文章父级的附件资源,没有关联WooCommerce的商品数据结构,自然无法正确输出商品图片。


完整插件实现代码

在WordPress站点的wp-content/plugins/目录下新建文件夹wc-single-product-gallery,在文件夹内新建主文件wc-single-product-gallery.php,写入以下代码:

<?php
/**
 * Plugin Name: WooCommerce 单商品图片展示
 * Description: 展示站点唯一的WooCommerce商品的全部图片画廊
 * Version: 1.0
 * License: GPL2
 */

// 直接访问文件时退出
if (!defined('ABSPATH')) {
    exit;
}

// 判断WooCommerce已启用才运行插件逻辑
if (in_array('woocommerce/woocommerce.php', apply_filters('active_plugins', get_option('active_plugins')))) {

    // 注册前端可用短代码
    add_shortcode('wc_single_product_gallery', 'wc_render_single_product_gallery');
    function wc_render_single_product_gallery($atts) {
        // 站点只有1款商品,直接取首个发布状态的商品
        $product_args = array(
            'post_type' => 'product',
            'post_status' => 'publish',
            'posts_per_page' => 1,
            'orderby' => 'date',
            'order' => 'DESC'
        );
        $products = get_posts($product_args);
        
        if (empty($products)) {
            return '<p>暂无可展示的商品</p>';
        }

        // 获取商品对象
        $product = wc_get_product($products[0]->ID);
        // 合并商品主图ID和图库图片ID
        $gallery_image_ids = array_merge(array($product->get_image_id()), $product->get_gallery_image_ids());
        // 去重避免主图重复展示
        $gallery_image_ids = array_unique($gallery_image_ids);

        if (empty($gallery_image_ids)) {
            return '<p>该商品暂未上传图片</p>';
        }

        // 生成gallery短代码调用,输出符合站点默认样式的图片画廊
        $gallery_shortcode = '[gallery ids="' . implode(',', $gallery_image_ids) . '"]';
        return apply_filters('the_content', $gallery_shortcode);
    }
}

使用方法

  1. 进入WordPress后台插件列表,启用「WooCommerce 单商品图片展示」插件
  2. 在需要展示商品图片的页面、文章中,插入短代码 [wc_single_product_gallery] 即可自动渲染商品图片画廊

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 00:24:04