首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Woocommerce在删除产品时,还会自动删除产品库和产品图片

Woocommerce在删除产品时,还会自动删除产品库和产品图片
EN

Stack Overflow用户
提问于 2014-07-10 20:26:43
回答 5查看 10.3K关注 0票数 2

我尝试了以下几种方法:

当一个产品页面被删除(永久)时,它也应该删除贴在帖子上的:产品图库和产品图像。

我尝试了我在https://wordpress.stackexchange.com/questions/109793/delete-associated-media-upon-page-deletion上找到的解决方案

但这对我来说并不管用。

EN

回答 5

Stack Overflow用户

发布于 2017-09-01 18:38:43

虽然这是一个古老的问题,但我将把它留在这里,以防将来有人会寻找它。

由于您想要删除产品图像,您可以尝试使用这些简洁方便的woocommerce函数来获取附件ids。

如下所示:

代码语言:javascript
运行
复制
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;
    }

    $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 );
        }
    }
}

对我来说很好。

票数 9
EN

Stack Overflow用户

发布于 2016-03-26 06:08:41

代码语言:javascript
运行
复制
add_action("before_delete_post","wdm_delete_post_images",10,1);

function wdm_delete_post_images($post_id)
{
 global $wpdb;
          $args = array(
                'post_parent' => $post_id,
                'post_type'   => 'attachment', 
                'numberposts' => -1,
                'post_status' => 'any' 
        ); 
        $childrens = get_children( $args);
        if($childrens):
            foreach($childrens as $attachment):   
             wp_delete_attachment( $attachment->ID, true ); 
             $wpdb->query("DELETE FROM {$wpdb->postmeta} WHERE post_id = ".$attachment->ID);
             wp_delete_post($attachment->ID,true ); 
            endforeach;

        endif;
}
票数 2
EN

Stack Overflow用户

发布于 2014-07-10 22:13:01

您可以尝试以下操作:

代码语言:javascript
运行
复制
add_action('after_delete_post','wdm_delete_post_images',10,1);

function wdm_delete_post_images($post_id)
{
   $featured_image_id = get_post_meta($post_id,'_thumbnail_id',true);

   $image_galleries_id = get_post_meta($post_id,'_product_image_gallery',true);

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

  if(!empty($image_galleries_id))
  {
    $image_galleries_array = split(',',$image_galleries_id);

    foreach($image_galleries_array as $single_image_id)
    {
        wp_delete_post($single_image_id);
    }
  }
}

当产品被永久删除时,这将删除图像。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24676547

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档