WC_API_Products::edit_product_category()publicWC 2.5.0

Edit a product category.

Method of the class: WC_API_Products{}

Return

Array|WP_Error. Product category if succeed, otherwise WP_Error will be returned

Usage

$WC_API_Products = new WC_API_Products();
$WC_API_Products->edit_product_category( $id, $data );
$id(int) (required)
Product category term ID
$data(array) (required)
Posted data

Changelog

Since 2.5.0 Introduced.

WC_API_Products::edit_product_category() code WC 8.7.0

public function edit_product_category( $id, $data ) {
	global $wpdb;

	try {
		if ( ! isset( $data['product_category'] ) ) {
			throw new WC_API_Exception( 'woocommerce_api_missing_product_category', sprintf( __( 'No %1$s data specified to edit %1$s', 'woocommerce' ), 'product_category' ), 400 );
		}

		$id   = absint( $id );
		$data = $data['product_category'];

		// Check permissions.
		if ( ! current_user_can( 'manage_product_terms' ) ) {
			throw new WC_API_Exception( 'woocommerce_api_user_cannot_edit_product_category', __( 'You do not have permission to edit product categories', 'woocommerce' ), 401 );
		}

		$data     = apply_filters( 'woocommerce_api_edit_product_category_data', $data, $this );
		$category = $this->get_product_category( $id );

		if ( is_wp_error( $category ) ) {
			return $category;
		}

		if ( isset( $data['image'] ) ) {
			$image_id = 0;

			// If value of image is numeric, assume value as image_id.
			$image = $data['image'];
			if ( is_numeric( $image ) ) {
				$image_id = absint( $image );
			} elseif ( ! empty( $image ) ) {
				$upload   = $this->upload_product_category_image( esc_url_raw( $image ) );
				$image_id = $this->set_product_category_image_as_attachment( $upload );
			}

			// In case client supplies invalid image or wants to unset category image.
			if ( ! wp_attachment_is_image( $image_id ) ) {
				$image_id = '';
			}
		}

		$update = wp_update_term( $id, 'product_cat', $data );
		if ( is_wp_error( $update ) ) {
			throw new WC_API_Exception( 'woocommerce_api_cannot_edit_product_category', __( 'Could not edit the category', 'woocommerce' ), 400 );
		}

		if ( ! empty( $data['display'] ) ) {
			update_term_meta( $id, 'display_type', 'default' === $data['display'] ? '' : sanitize_text_field( $data['display'] ) );
		}

		if ( isset( $image_id ) ) {
			update_term_meta( $id, 'thumbnail_id', $image_id );
		}

		do_action( 'woocommerce_api_edit_product_category', $id, $data );

		return $this->get_product_category( $id );
	} catch ( WC_API_Exception $e ) {
		return new WP_Error( $e->getErrorCode(), $e->getMessage(), array( 'status' => $e->getCode() ) );
	}
}