WC_API_Products::delete_product_attribute()publicWC 2.5.0

Delete a product attribute.

Метод класса: WC_API_Products{}

Возвращает

Массив|WP_Error.

Использование

$WC_API_Products = new WC_API_Products();
$WC_API_Products->delete_product_attribute( $id );
$id(int) (обязательный)
the product attribute ID.

Список изменений

С версии 2.5.0 Введена.

Код WC_API_Products::delete_product_attribute() WC 8.7.0

public function delete_product_attribute( $id ) {
	global $wpdb;

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

		$id = absint( $id );

		$attribute_name = $wpdb->get_var( $wpdb->prepare( "
			SELECT attribute_name
			FROM {$wpdb->prefix}woocommerce_attribute_taxonomies
			WHERE attribute_id = %d
		 ", $id ) );

		if ( is_null( $attribute_name ) ) {
			throw new WC_API_Exception( 'woocommerce_api_invalid_product_attribute_id', __( 'A product attribute with the provided ID could not be found', 'woocommerce' ), 404 );
		}

		$deleted = $wpdb->delete(
			$wpdb->prefix . 'woocommerce_attribute_taxonomies',
			array( 'attribute_id' => $id ),
			array( '%d' )
		);

		if ( false === $deleted ) {
			throw new WC_API_Exception( 'woocommerce_api_cannot_delete_product_attribute', __( 'Could not delete the attribute', 'woocommerce' ), 401 );
		}

		$taxonomy = wc_attribute_taxonomy_name( $attribute_name );

		if ( taxonomy_exists( $taxonomy ) ) {
			$terms = get_terms( $taxonomy, 'orderby=name&hide_empty=0' );
			foreach ( $terms as $term ) {
				wp_delete_term( $term->term_id, $taxonomy );
			}
		}

		do_action( 'woocommerce_attribute_deleted', $id, $attribute_name, $taxonomy );
		do_action( 'woocommerce_api_delete_product_attribute', $id, $this );

		// Clear transients.
		wp_schedule_single_event( time(), 'woocommerce_flush_rewrite_rules' );
		delete_transient( 'wc_attribute_taxonomies' );
		WC_Cache_Helper::invalidate_cache_group( 'woocommerce-attributes' );

		return array( 'message' => sprintf( __( 'Deleted %s', 'woocommerce' ), 'product_attribute' ) );
	} catch ( WC_API_Exception $e ) {
		return new WP_Error( $e->getErrorCode(), $e->getMessage(), array( 'status' => $e->getCode() ) );
	}
}