Created
April 25, 2019 18:04
-
-
Save mtruitt/8e2fae133ef15706bb4728d11d9e9dcf to your computer and use it in GitHub Desktop.
Deletes a product
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| function deleteProduct($id, $force = FALSE) { | |
| $product = wc_get_product($id); | |
| if(empty($product)) | |
| return new WP_Error(999, sprintf(__('No %s is associated with #%d', 'woocommerce'), 'product', $id)); | |
| // If we're forcing, then delete permanently. | |
| if ($force) { | |
| if ($product->is_type('variable')) { | |
| foreach ($product->get_children() as $child_id) { | |
| $child = wc_get_product($child_id); | |
| $child->delete(true); | |
| } | |
| } elseif ($product->is_type('grouped')) { | |
| foreach ($product->get_children() as $child_id) { | |
| $child = wc_get_product($child_id); | |
| $child->set_parent_id(0); | |
| $child->save(); | |
| } | |
| } | |
| $product->delete(true); | |
| $result = $product->get_id() > 0 ? false : true; | |
| } else { | |
| $product->delete(); | |
| $result = 'trash' === $product->get_status(); | |
| } | |
| if (!$result) { | |
| return new WP_Error(999, sprintf(__('This %s cannot be deleted', 'woocommerce'), 'product')); | |
| } | |
| // Delete parent product transients. | |
| if ($parent_id = wp_get_post_parent_id($id)) { | |
| wc_delete_product_transients($parent_id); | |
| } | |
| return true; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment