WC_API_Products::create_product_attribute_term( int $attribute_id, array $data )
Create a new product attribute term.
Description Description
Parameters Parameters
- $attribute_id
-
(Required) Attribute ID.
- $data
-
(Required) Posted data.
Return Return
(array|WP_Error)
Source Source
File: includes/legacy/api/v3/class-wc-api-products.php
public function create_product_attribute_term( $attribute_id, $data ) {
global $wpdb;
try {
if ( ! isset( $data['product_attribute_term'] ) ) {
throw new WC_API_Exception( 'woocommerce_api_missing_product_attribute_term_data', sprintf( __( 'No %1$s data specified to create %1$s', 'woocommerce' ), 'product_attribute_term' ), 400 );
}
$data = $data['product_attribute_term'];
// Check permissions.
if ( ! current_user_can( 'manage_product_terms' ) ) {
throw new WC_API_Exception( 'woocommerce_api_user_cannot_create_product_attribute', __( 'You do not have permission to create product attributes', 'woocommerce' ), 401 );
}
$taxonomy = wc_attribute_taxonomy_name_by_id( $attribute_id );
if ( ! $taxonomy ) {
throw new WC_API_Exception( 'woocommerce_api_invalid_product_attribute_id', __( 'A product attribute with the provided ID could not be found', 'woocommerce' ), 404 );
}
$data = apply_filters( 'woocommerce_api_create_product_attribute_term_data', $data, $this );
// Check if attribute term name is specified.
if ( ! isset( $data['name'] ) ) {
throw new WC_API_Exception( 'woocommerce_api_missing_product_attribute_term_name', sprintf( __( 'Missing parameter %s', 'woocommerce' ), 'name' ), 400 );
}
$args = array();
// Set the attribute term slug.
if ( isset( $data['slug'] ) ) {
$args['slug'] = sanitize_title( wp_unslash( $data['slug'] ) );
}
$term = wp_insert_term( $data['name'], $taxonomy, $args );
// Checks for an error in the term creation.
if ( is_wp_error( $term ) ) {
throw new WC_API_Exception( 'woocommerce_api_cannot_create_product_attribute', $term->get_error_message(), 400 );
}
$id = $term['term_id'];
do_action( 'woocommerce_api_create_product_attribute_term', $id, $data );
$this->server->send_status( 201 );
return $this->get_product_attribute_term( $attribute_id, $id );
} catch ( WC_API_Exception $e ) {
return new WP_Error( $e->getErrorCode(), $e->getMessage(), array( 'status' => $e->getCode() ) );
}
}
Changelog Changelog
| Version | Description |
|---|---|
| 2.5.0 | Introduced. |