WC_API_Products::create_product_category( array $data )
Create a new product category.
Description Description
Parameters Parameters
- $data
-
(Required) Posted data
Return Return
(array|WP_Error) Product category if succeed, otherwise WP_Error will be returned
Source Source
File: includes/legacy/api/v3/class-wc-api-products.php
public function create_product_category( $data ) { global $wpdb; try { if ( ! isset( $data['product_category'] ) ) { throw new WC_API_Exception( 'woocommerce_api_missing_product_category_data', sprintf( __( 'No %1$s data specified to create %1$s', 'woocommerce' ), 'product_category' ), 400 ); } // Check permissions if ( ! current_user_can( 'manage_product_terms' ) ) { throw new WC_API_Exception( 'woocommerce_api_user_cannot_create_product_category', __( 'You do not have permission to create product categories', 'woocommerce' ), 401 ); } $defaults = array( 'name' => '', 'slug' => '', 'description' => '', 'parent' => 0, 'display' => 'default', 'image' => '', ); $data = wp_parse_args( $data['product_category'], $defaults ); $data = apply_filters( 'woocommerce_api_create_product_category_data', $data, $this ); // Check parent. $data['parent'] = absint( $data['parent'] ); if ( $data['parent'] ) { $parent = get_term_by( 'id', $data['parent'], 'product_cat' ); if ( ! $parent ) { throw new WC_API_Exception( 'woocommerce_api_invalid_product_category_parent', __( 'Product category parent is invalid', 'woocommerce' ), 400 ); } } // If value of image is numeric, assume value as image_id. $image = $data['image']; $image_id = 0; 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 ); } $insert = wp_insert_term( $data['name'], 'product_cat', $data ); if ( is_wp_error( $insert ) ) { throw new WC_API_Exception( 'woocommerce_api_cannot_create_product_category', $insert->get_error_message(), 400 ); } $id = $insert['term_id']; update_term_meta( $id, 'display_type', 'default' === $data['display'] ? '' : sanitize_text_field( $data['display'] ) ); // Check if image_id is a valid image attachment before updating the term meta. if ( $image_id && wp_attachment_is_image( $image_id ) ) { update_term_meta( $id, 'thumbnail_id', $image_id ); } do_action( 'woocommerce_api_create_product_category', $id, $data ); $this->server->send_status( 201 ); return $this->get_product_category( $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. |