WC_API_Products::delete_product( int $id, bool $force = false )
Delete a product.
Description Description
Parameters Parameters
- $id
-
(Required) the product ID.
- $force
-
(Optional) true to permanently delete order, false to move to trash.
Default value: false
Return Return
(array|WP_Error)
Source Source
File: includes/legacy/api/v2/class-wc-api-products.php
public function delete_product( $id, $force = false ) {
$id = $this->validate_request( $id, 'product', 'delete' );
if ( is_wp_error( $id ) ) {
return $id;
}
$product = wc_get_product( $id );
do_action( 'woocommerce_api_delete_product', $id, $this );
// 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 );
if ( ! empty( $child ) ) {
$child->delete( true );
}
}
} else {
// For other product types, if the product has children, remove the relationship.
foreach ( $product->get_children() as $child_id ) {
$child = wc_get_product( $child_id );
if ( ! empty( $child ) ) {
$child->set_parent_id( 0 );
$child->save();
}
}
}
$product->delete( true );
$result = ! ( $product->get_id() > 0 );
} else {
$product->delete();
$result = 'trash' === $product->get_status();
}
if ( ! $result ) {
return new WP_Error( 'woocommerce_api_cannot_delete_product', sprintf( __( 'This %s cannot be deleted', 'woocommerce' ), 'product' ), array( 'status' => 500 ) );
}
// Delete parent product transients.
if ( $parent_id = wp_get_post_parent_id( $id ) ) {
wc_delete_product_transients( $parent_id );
}
if ( $force ) {
return array( 'message' => sprintf( __( 'Permanently deleted %s', 'woocommerce' ), 'product' ) );
} else {
$this->server->send_status( '202' );
return array( 'message' => sprintf( __( 'Deleted %s', 'woocommerce' ), 'product' ) );
}
}
Changelog Changelog
| Version | Description |
|---|---|
| 2.2 | Introduced. |