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

WooCommerce Storefront子主题:单品页头部下方添加全屏特色图求助

在Storefront子主题单产品页添加独立主图区块

直接将以下代码添加到你的Storefront子主题functions.php文件中:

// 在单个产品页面头部下方插入独立主图区块
add_action( 'woocommerce_after_single_product_summary', 'custom_single_product_top_image', 5 );
function custom_single_product_top_image() {
    global $product;
    
    // 仅在单个产品页面执行
    if ( ! is_product() ) return;
    
    // 获取产品主图ID
    $main_image_id = $product->get_image_id();
    
    // 无主图则终止
    if ( ! $main_image_id ) return;
    
    // 调用指定尺寸的主图,可替换为自定义尺寸名称
    $image_url = wp_get_attachment_image_url( $main_image_id, 'large' );
    $image_alt = get_post_meta( $main_image_id, '_wp_attachment_image_alt', true );
    
    // 输出带独立ID的容器
    echo '<div id="custom-product-top-image" class="custom-product-image-container">';
        echo '<img src="' . esc_url( $image_url ) . '" alt="' . esc_attr( $image_alt ) . '" />';
    echo '</div>';
}

// 可选:注册自定义图片尺寸(按需使用)
add_action( 'after_setup_theme', 'custom_product_image_size' );
function custom_product_image_size() {
    // 注册宽800px、高600px的裁剪尺寸,可自行修改参数
    add_image_size( 'custom-product-top', 800, 600, true );
}

代码说明

  • 使用woocommerce_after_single_product_summary钩子,优先级设为5,确保区块显示在产品价格、描述等内容之前,紧贴页面头部下方
  • 若需要特定尺寸的图片,取消注释第二部分代码,注册自定义尺寸后,将第一部分代码中的'large'替换为'custom-product-top'
  • 生成的区块带有独立IDcustom-product-top-image,完全独立于默认产品图库,不会互相影响

自定义样式示例

在子主题的style.css中添加CSS,自由控制区块样式:

#custom-product-top-image {
    max-width: 900px;
    margin: 0 auto 2.5rem;
    padding: 0 1rem;
}

#custom-product-top-image img {
    width: 100%;
    height: auto;
    max-width: none; /* 解除默认max-width限制 */
    border-radius: 4px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

注意事项

  • 所有代码必须添加到子主题文件中,避免父主题更新导致代码丢失
  • 注册自定义尺寸后,需使用Regenerate Thumbnails插件重新生成对应尺寸的图片

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 05:24:21