WC_API_Products::get_product_attribute()publicWC 2.5.0

Get the product attribute for the given ID

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

Хуки из метода

Возвращает

Массив|WP_Error.

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

$WC_API_Products = new WC_API_Products();
$WC_API_Products->get_product_attribute( $id, $fields );
$id(строка) (обязательный)
product attribute term ID
$fields(строка|null)
fields to limit response to
По умолчанию: null

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

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

Код WC_API_Products::get_product_attribute() WC 8.7.0

public function get_product_attribute( $id, $fields = null ) {
	global $wpdb;

	try {
		$id = absint( $id );

		// Validate ID
		if ( empty( $id ) ) {
			throw new WC_API_Exception( 'woocommerce_api_invalid_product_attribute_id', __( 'Invalid product attribute ID', 'woocommerce' ), 400 );
		}

		// Permissions check
		if ( ! current_user_can( 'manage_product_terms' ) ) {
			throw new WC_API_Exception( 'woocommerce_api_user_cannot_read_product_attributes', __( 'You do not have permission to read product attributes', 'woocommerce' ), 401 );
		}

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

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

		$product_attribute = array(
			'id'           => intval( $attribute->attribute_id ),
			'name'         => $attribute->attribute_label,
			'slug'         => wc_attribute_taxonomy_name( $attribute->attribute_name ),
			'type'         => $attribute->attribute_type,
			'order_by'     => $attribute->attribute_orderby,
			'has_archives' => (bool) $attribute->attribute_public,
		);

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