如何在woocommerce删除产品的同时删除产品图片

默认woocommerce删除产品的时候,产品图片是不会被删除的。为了节省服务器空间,我们有时候希望在删除产品的时候也能同时把产品图片删除。

方法是在functions里添加如下代码:

// Automatically Delete Woocommerce Images After Deleting a Product
add_action( 'before_delete_post', 'delete_product_images', 10, 1 );
 
function delete_product_images( $post_id ) {
        // Check if user has the capability to delete products
        if ( !current_user_can( 'delete_products' ) ) {
            return;
        }
    $product = wc_get_product( $post_id );
 
    if ( !$product ) {
        return;
    }
 
    $featured_image_id = $product->get_image_id();
    $image_galleries_id = $product->get_gallery_image_ids();
 
    if( !empty( $featured_image_id ) ) {
        $is_featured_image_used = is_image_used( $featured_image_id, $post_id );
        if ( !$is_featured_image_used ) {
            wp_delete_attachment( $featured_image_id, true );
        }
    }
 
    if( !empty( $image_galleries_id ) ) {
        foreach( $image_galleries_id as $single_image_id ) {
            $is_image_used = is_image_used( $single_image_id, $post_id );
            if ( !$is_image_used ) {
                wp_delete_attachment( $single_image_id, true );
            }
        }
    }
}
 
function is_image_used( $image_id, $current_product_id ) {
    $query = new WP_Query( array(
        'post_type' => 'product',
        'post_status' => 'publish',
        'meta_query' => array(
            'relation' => 'OR',
            array(
                'key' => '_thumbnail_id',
                'value' => $image_id,
                'compare' => '='
            ),
            array(
                'key' => '_product_image_gallery',
                'value' => '"'.$image_id.'"',
                'compare' => 'LIKE'
            )
        ),
        'post__not_in' => array( $current_product_id ),
        'fields' => 'ids',
        'posts_per_page' => -1
    ) );
 
    return ( $query->have_posts() );
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值