WC_API_Products::create_product_attribute()publicWC 2.5.0

Create a new product attribute.

Method of the class: WC_API_Products{}

Return

Array|WP_Error.

Usage

$WC_API_Products = new WC_API_Products();
$WC_API_Products->create_product_attribute( $data );
$data(array) (required)
Posted data.

Changelog

Since 2.5.0 Introduced.

WC_API_Products::create_product_attribute() code WC 8.7.0

public function create_product_attribute( $data ) {
	global $wpdb;

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

		$data = $data['product_attribute'];

		// 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 );
		}

		$data = apply_filters( 'woocommerce_api_create_product_attribute_data', $data, $this );

		if ( ! isset( $data['name'] ) ) {
			$data['name'] = '';
		}

		// Set the attribute slug.
		if ( ! isset( $data['slug'] ) ) {
			$data['slug'] = wc_sanitize_taxonomy_name( stripslashes( $data['name'] ) );
		} else {
			$data['slug'] = preg_replace( '/^pa\_/', '', wc_sanitize_taxonomy_name( stripslashes( $data['slug'] ) ) );
		}

		// Set attribute type when not sent.
		if ( ! isset( $data['type'] ) ) {
			$data['type'] = 'select';
		}

		// Set order by when not sent.
		if ( ! isset( $data['order_by'] ) ) {
			$data['order_by'] = 'menu_order';
		}

		// Validate the attribute data.
		$this->validate_attribute_data( $data['name'], $data['slug'], $data['type'], $data['order_by'], true );

		$insert = $wpdb->insert(
			$wpdb->prefix . 'woocommerce_attribute_taxonomies',
			array(
				'attribute_label'   => $data['name'],
				'attribute_name'    => $data['slug'],
				'attribute_type'    => $data['type'],
				'attribute_orderby' => $data['order_by'],
				'attribute_public'  => isset( $data['has_archives'] ) && true === $data['has_archives'] ? 1 : 0,
			),
			array( '%s', '%s', '%s', '%s', '%d' )
		);

		// Checks for an error in the product creation.
		if ( is_wp_error( $insert ) ) {
			throw new WC_API_Exception( 'woocommerce_api_cannot_create_product_attribute', $insert->get_error_message(), 400 );
		}

		$id = $wpdb->insert_id;

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

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

		$this->server->send_status( 201 );

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