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

如何修改WooCommerce代码实现仅删除父商品时触发删图,变体不触发?

WooCommerce删除商品时仅父商品触发关联图片删除的调整方案

修改思路

WooCommerce 中商品变体的内置类型标识为variation,我们只需在原有代码中增加类型判断逻辑,识别到当前删除的是商品变体时直接终止函数执行,即可避免变体删除时误删关联图片。

修改后完整代码

// Automatically Delete Woocommerce Images After Deleting a Product
add_action( 'before_delete_post', 'delete_product_images', 10, 1 );

function delete_product_images( $post_id )
{
    $product = wc_get_product( $post_id );

    if ( !$product ) {
        return;
    }

    // 新增:商品变体直接跳过删除逻辑
    if ( $product->is_type( 'variation' ) ) {
        return;
    }

    $featured_image_id = $product->get_image_id();
    $image_galleries_id = $product->get_gallery_image_ids();

    if( !empty( $featured_image_id ) ) {
        wp_delete_post( $featured_image_id );
    }

    if( !empty( $image_galleries_id ) ) {
        foreach( $image_galleries_id as $single_image_id ) {
            wp_delete_post( $single_image_id );
        }
    }
}

可选优化

如果需要进一步限制仅特定类型的父商品触发图片删除,可将上述新增的判断代码替换为以下内容,自行调整允许触发的商品类型即可:

// 仅简单商品、可变商品删除时触发图片删除,其他类型全部跳过
if ( ! $product->is_type( [ 'simple', 'variable' ] ) ) {
    return;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 17:45:07