WC_API_Products::get_product_category()publicWC 2.2

Get the product category for the given ID

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

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

Возвращает

Массив|WP_Error.

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

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

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

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

Код WC_API_Products::get_product_category() WC 8.7.0

public function get_product_category( $id, $fields = null ) {
	try {
		$id = absint( $id );

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

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

		$term = get_term( $id, 'product_cat' );

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

		$term_id = intval( $term->term_id );

		// Get category display type
		$display_type = get_term_meta( $term_id, 'display_type', true );

		// Get category image
		$image = '';
		if ( $image_id = get_term_meta( $term_id, 'thumbnail_id', true ) ) {
			$image = wp_get_attachment_url( $image_id );
		}

		$product_category = array(
			'id'          => $term_id,
			'name'        => $term->name,
			'slug'        => $term->slug,
			'parent'      => $term->parent,
			'description' => $term->description,
			'display'     => $display_type ? $display_type : 'default',
			'image'       => $image ? esc_url( $image ) : '',
			'count'       => intval( $term->count ),
		);

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