Search
Remove Linked Products Automatically When Deleting a Main Product in WooCommerce - WP Global Cart
17558
documentation-template-default,single,single-documentation,postid-17558,theme-awake,eltd-core-1.1,woocommerce-no-js,awake child-child-ver-1.0.0,awake-ver-1.0,eltd-smooth-scroll,eltd-smooth-page-transitions,eltd-mimic-ajax,eltd-grid-1200,eltd-blog-installed,eltd-default-style,eltd-fade-push-text-top,eltd-header-standard,eltd-sticky-header-on-scroll-down-up,eltd-default-mobile-header,eltd-sticky-up-mobile-header,eltd-menu-item-first-level-bg-color,eltd-dropdown-slide-from-top,eltd-,eltd-fullscreen-search eltd-search-fade,eltd-side-menu-slide-from-right,wpb-js-composer js-comp-ver-6.3.0,vc_responsive
 

Remove Linked Products Automatically When Deleting a Main Product in WooCommerce

WP Global Cart / Remove Linked Products Automatically When Deleting a Main Product in WooCommerce
Share on FacebookTweet about this on TwitterShare on Google+Share on LinkedInShare on TumblrPin on PinterestEmail this to someonePrint this page

Remove Linked Products Automatically When Deleting a Main Product in WooCommerce

By default, WooCommerce retains synchronized products when a main product is deleted. However, you may want to change this behavior to automatically remove synchronized child products when the main product is deleted. This can be achieved by adding custom code to your site.

Here’s how you can implement this functionality:

add_action( 'before_delete_post', 'wogc_before_delete_post', 1, 2 );

/**
 * Remove synchronized child products when a main product is deleted.
 *
 * @param int $postid The ID of the product being deleted.
 * @param WP_Post $post The WordPress post object for the product.
 */
function wogc_before_delete_post( $postid, $post ) {
    // Check if the product is a main product
    if ( ! $this->PS->is_main_product( $postid ) ) {
        return;
    }
    
    global $blog_id;
    $main_product = new WooGC_PS_main_product( $postid );

    foreach ( $main_product->get_children() as $child_shop_id ) {
        $child_product_id = $this->PS->get_product_synchronized_at_shop( $postid, $blog_id, $child_shop_id );
        
        if ( $child_product_id > 0 ) {
            switch_to_blog( $child_shop_id );
            wp_delete_post( $child_product_id, false ); // Set to true to force deletion
            restore_current_blog();
        }
    }
}

Key Notes:

  • Hook: The before_delete_post action ensures the function runs before the main product is deleted.
  • Child Products: Linked child products are identified and removed using the get_children() method.
  • Multisite Handling: The code manages multisite setups by switching blogs during the deletion process.

Add this snippet to your theme’s functions.php file or a custom plugin to streamline product synchronization cleanup.

0
Would love your thoughts, please comment.x
()
x