. */ public const PRODUCT_FIELDS_FILTER = 'aipt_content_structure_product_fields'; /** * Filter resolving a product-scope ref this catalog does not resolve * itself (a `meta:` custom field): receives null, the ref and the * WC_Product, and returns array{type:string,value:mixed} or null. */ public const PRODUCT_VALUE_FILTER = 'aipt_content_structure_product_field_value'; /** * Filter resolving a term-scope ref this catalog lists but does not * resolve itself (the Business build's `term:common_attributes` and * `term:product_descriptions`): receives null, the ref and the WP_Term, * and returns array{type:string,value:mixed} or null. */ public const TERM_VALUE_FILTER = 'aipt_content_structure_term_field_value'; /** * Entries fetched for `term:top_products`: the upper bound a Blueprint's * own "Sample products per category" setting can ever request * (`DefinitionPrimitives::TAXONOMY_SAMPLE_PRODUCTS_MAX`), so the query * always has enough rows to draw from; the actual number shown is * narrowed afterward by `Context\TermContextBuilder::capSamples()`. */ private const TOP_PRODUCTS_LIMIT = 20; /** * Per-instance cache of forScope() results, keyed by scope. Avoids * repeating WC/DB discovery for every field checked during one * normalize() pass; never persisted beyond this object's lifetime so it * cannot leak state between requests or tests. * * @var array> */ private $scope_cache = array(); /** * Refs an already stored template holds that this request may not newly * add (a `meta:` field after a plan downgrade or a vanished custom * field). They stay on save and are clamped when a run resolves them. * * @var array */ private $stored_refs = array(); /** * Copy of this catalog that also accepts the `meta:` refs already present * in a stored definition, so saving an unrelated change is not rejected * for data the merchant did not touch. A ref added later is still checked. * * @param array $stored_definition Stored BlueprintDefinition. * @return self */ public function withStoredRefsOf( array $stored_definition ): self { $copy = clone $this; array_walk_recursive( $stored_definition, static function ( $value ) use ( $copy ): void { if ( is_string( $value ) && 0 === strpos( $value, 'meta:' ) ) { $copy->stored_refs[ $value ] = true; } } ); return $copy; } /** * Whether the ref was already stored in the definition being updated. * * @param string $ref FieldRef. * @return bool */ public function isStoredRef( string $ref ): bool { return isset( $this->stored_refs[ $ref ] ); } /** * Every known FieldRef for one scope. * * @param string $scope 'product' | 'term' | 'image'. * @return array */ public function forScope( string $scope ): array { if ( isset( $this->scope_cache[ $scope ] ) ) { return $this->scope_cache[ $scope ]; } switch ( $scope ) { case 'product': $fields = $this->productScopeFields(); break; case 'term': $fields = $this->termScopeFields(); break; case 'image': $fields = $this->imageScopeFields(); break; default: $fields = array(); break; } $this->scope_cache[ $scope ] = $fields; return $fields; } /** * Whether $ref is a known FieldRef for $scope. * * @param string $ref Candidate FieldRef. * @param string $scope 'product' | 'term' | 'image'. * @return bool */ public function isValidRef( string $ref, string $scope ): bool { foreach ( $this->forScope( $scope ) as $field ) { if ( $field['ref'] === $ref ) { return true; } } return false; } /** * Label for a FieldRef, resolved from its own scope (derived from the * ref's prefix). Returns '' when the ref is unknown. * * @param string $ref FieldRef. * @return string */ public function label( string $ref ): string { $scope = $this->scopeForRef( $ref ); if ( '' === $scope ) { return ''; } foreach ( $this->forScope( $scope ) as $field ) { if ( $field['ref'] === $ref ) { return $field['label']; } } return ''; } /** * Whether this install may use `meta:` field refs at all. * * Mirrors the existing custom-variable entitlement bridge exactly: free * installs get false, Premium registers the filter true for any paid * plan, grandfathered access included. * * @return bool */ public function customFieldsAllowed(): bool { return (bool) apply_filters( 'aipt_custom_variables_can_edit', false ); } /** * Resolve a product-scope FieldRef to a value. * * @param WC_Product $product Product. * @param string $ref FieldRef. * @return array{type:string,value:mixed,empty:bool} */ public function productValue( WC_Product $product, string $ref ): array { switch ( $ref ) { case 'core:name': return $this->text( $product->get_name() ); case 'core:short_description': return $this->text( HtmlToText::convert( (string) $product->get_short_description() ) ); case 'core:description': return $this->text( HtmlToText::convert( (string) $product->get_description() ) ); case 'core:sku': return $this->text( (string) $product->get_sku() ); case 'core:price': return $this->priceValue( $product->get_price() ); case 'core:regular_price': return $this->priceValue( $product->get_regular_price() ); case 'core:categories': return $this->list( $this->productCategoryNames( $product ) ); case 'core:tags': return $this->list( $this->productTermNames( $product, 'product_tag' ) ); case 'core:brand': return $this->brandValue( $product ); case 'core:weight': return $this->text( $this->weightText( $product ) ); case 'core:dimensions': return $this->text( $this->dimensionsText( $product ) ); case 'core:attributes': return $this->pairs( $this->productAttributePairs( $product ) ); case 'core:grouped_children': return $this->list( $this->groupedChildProductNames( $product ) ); default: if ( 0 === strpos( $ref, 'attr:' ) ) { return $this->text( $this->attributeValue( $product, substr( $ref, 5 ) ) ); } return $this->extensionValue( apply_filters( self::PRODUCT_VALUE_FILTER, null, $ref, $product ) ); } } /** * Every `attr:*` FieldRef this specific product has a non-empty value * for, in the product's own attribute order * (`WC_Product::get_attributes()`'s own key order) — reuses * `productValue()` for the value/empty check so the per-attribute * resolution logic stays in exactly one place. Labels for these refs * are resolved separately, through the existing `forScope('product')` / * `label()` catalog lookup "Selected attributes" mode already uses. * * Used by Specifications sections in "All attributes" mode so the * rendered table has one row per attribute the product actually * carries, instead of the blueprint-level source allowlist * (`SubjectContextResolver::dataFieldRefs()`). * * @param WC_Product $product Product. * @return string[] Ordered `attr:*` refs. */ public function attributeRefsForProduct( WC_Product $product ): array { $refs = array(); foreach ( array_keys( (array) $product->get_attributes() ) as $name ) { $ref = 'attr:' . $name; if ( empty( $this->productValue( $product, $ref )['empty'] ) ) { $refs[] = $ref; } } return $refs; } /** * Every `attr:*` FieldRef `attributeRefsForProduct()` would return for * this product, mapped to the label resolved directly from THIS * product (`wc_attribute_label($name, $product)`, with the same * ucwords() fallback `productAttributePairs()` already uses when that * resolves empty) — independent of FieldCatalog's bounded, store-wide * discovery sample (`productAttributeRefs()`, which backs `label()` / * `forScope('product')`). * * A per-attribute Specifications row (Specifications sections in "All * attributes" mode) must label itself from the product that actually * carries the attribute, not from a sample of up to 50 OTHER products: * a local/custom attribute this product carries but that sample never * happened to see would otherwise resolve to a blank label (audit item * `specs-attribute-label-blank-for-undiscovered-local-attribute`). * * @param WC_Product $product Product. * @return array Ref => label, in the product's own attribute order. */ public function attributeRefLabelsForProduct( WC_Product $product ): array { $labels = array(); foreach ( array_keys( (array) $product->get_attributes() ) as $name ) { $ref = 'attr:' . $name; if ( empty( $this->productValue( $product, $ref )['empty'] ) ) { $labels[ $ref ] = $this->attributeLabelForProduct( $product, $name ); } } return $labels; } /** * Resolve a term-scope FieldRef to a value. * * @param WP_Term $term Term. * @param string $ref FieldRef. * @return array{type:string,value:mixed,empty:bool} */ public function termValue( WP_Term $term, string $ref ): array { switch ( $ref ) { case 'term:name': return $this->text( (string) $term->name ); case 'term:description': return $this->text( HtmlToText::convert( (string) $term->description ) ); case 'term:parent': return $this->text( $this->parentTermName( $term ) ); case 'term:children': return $this->list( $this->childTermNames( $term ) ); case 'term:product_count': return $this->text( (string) TermProductSampler::countCatalogProducts( (string) $term->taxonomy, (string) $term->slug, (int) $term->count ) ); case 'term:top_products': return $this->list( $this->topProductNames( $term ) ); default: return $this->extensionValue( apply_filters( self::TERM_VALUE_FILTER, null, $ref, $term ) ); } } /** * A value an extension resolved for a ref this catalog does not resolve * itself (product or term scope), rebuilt through the same helpers as every other value so its * shape always holds; anything else is an empty text. * * @param mixed $value array{type:string,value:mixed} or null. * @return array{type:string,value:mixed,empty:bool} */ private function extensionValue( $value ): array { $type = is_array( $value ) ? (string) ( $value['type'] ?? '' ) : ''; $raw = is_array( $value ) ? ( $value['value'] ?? null ) : null; switch ( $type ) { case 'pairs': $pairs = array(); foreach ( is_array( $raw ) ? $raw : array() as $pair ) { if ( is_array( $pair ) && is_scalar( $pair['label'] ?? null ) && is_scalar( $pair['value'] ?? null ) && '' !== trim( (string) $pair['value'] ) ) { $pairs[] = array( 'label' => (string) $pair['label'], 'value' => (string) $pair['value'] ); } } return $this->pairs( $pairs ); case 'list': return $this->list( is_array( $raw ) ? $raw : array() ); case 'text': return $this->text( is_scalar( $raw ) ? (string) $raw : '' ); default: return $this->text( '' ); } } /** * Resolve an image-scope FieldRef to a value. * * The parent product id is part of this method's contract * so future attachment-scope refs can read parent-product * context without changing the signature; no current ref needs it. * * @param int $attachment_id Attachment id. * @param int $product_id Parent product id (reserved, see above). * @param int $position 0-based position among the product's images. * @param string $ref FieldRef. * @return array{type:string,value:mixed,empty:bool} */ public function imageValue( int $attachment_id, int $product_id, int $position, string $ref ): array { unset( $product_id ); switch ( $ref ) { case 'image:position': return $this->text( (string) $position ); case 'image:filename': $path = (string) get_attached_file( $attachment_id ); return $this->text( '' !== $path ? wp_basename( $path ) : '' ); case 'image:title': return $this->text( (string) get_the_title( $attachment_id ) ); case 'image:caption': return $this->text( (string) wp_get_attachment_caption( $attachment_id ) ); case 'image:existing_alt': return $this->text( (string) get_post_meta( $attachment_id, '_wp_attachment_image_alt', true ) ); default: return $this->text( '' ); } } /** * Product-scope catalog entries: fixed core fields, discovered * attributes, and (only when entitled) allowlisted custom fields. * * @return array */ private function productScopeFields(): array { $fields = array( array( 'ref' => 'core:name', 'label' => __( 'Product name', 'ai-product-tools' ), 'group' => 'core', 'description' => __( 'The product title.', 'ai-product-tools' ) ), array( 'ref' => 'core:short_description', 'label' => __( 'Short description', 'ai-product-tools' ), 'group' => 'core', 'description' => __( 'The existing short description.', 'ai-product-tools' ) ), array( 'ref' => 'core:description', 'label' => __( 'Long description', 'ai-product-tools' ), 'group' => 'core', 'description' => __( 'The existing long description. Off by default: older copy may contain claims you no longer make.', 'ai-product-tools' ) ), array( 'ref' => 'core:sku', 'label' => __( 'SKU', 'ai-product-tools' ), 'group' => 'core', 'description' => __( 'The product SKU.', 'ai-product-tools' ) ), array( 'ref' => 'core:price', 'label' => __( 'Price', 'ai-product-tools' ), 'group' => 'core', 'description' => __( 'The current selling price, as plain text.', 'ai-product-tools' ) ), array( 'ref' => 'core:regular_price', 'label' => __( 'Regular price', 'ai-product-tools' ), 'group' => 'core', 'description' => __( 'The regular (non-sale) price, as plain text.', 'ai-product-tools' ) ), array( 'ref' => 'core:categories', 'label' => __( 'Categories', 'ai-product-tools' ), 'group' => 'core', 'description' => __( 'Assigned product categories.', 'ai-product-tools' ) ), array( 'ref' => 'core:tags', 'label' => __( 'Tags', 'ai-product-tools' ), 'group' => 'core', 'description' => __( 'Assigned product tags.', 'ai-product-tools' ) ), array( 'ref' => 'core:brand', 'label' => __( 'Brand', 'ai-product-tools' ), 'group' => 'core', 'description' => __( 'The product brand from WooCommerce Brands, or a Brand attribute when the store keeps brands there.', 'ai-product-tools' ) ), array( 'ref' => 'core:weight', 'label' => __( 'Weight', 'ai-product-tools' ), 'group' => 'core', 'description' => __( 'Product weight with its store unit.', 'ai-product-tools' ) ), array( 'ref' => 'core:dimensions', 'label' => __( 'Dimensions', 'ai-product-tools' ), 'group' => 'core', 'description' => __( 'Length x width x height with the store unit.', 'ai-product-tools' ) ), array( 'ref' => 'core:attributes', 'label' => __( 'All attributes', 'ai-product-tools' ), 'group' => 'core', 'description' => __( 'Every product attribute, as label and value pairs.', 'ai-product-tools' ) ), array( 'ref' => 'core:grouped_children', 'label' => __( 'Included products', 'ai-product-tools' ), 'group' => 'core', 'description' => __( 'For a grouped product, the names of the products it includes. Empty for every other product type.', 'ai-product-tools' ) ), ); foreach ( $this->productAttributeRefs() as $ref => $label ) { $fields[] = array( 'ref' => $ref, 'label' => $label, 'group' => 'attribute', 'description' => __( 'A single product attribute.', 'ai-product-tools' ), ); } $extra = apply_filters( self::PRODUCT_FIELDS_FILTER, array() ); foreach ( is_array( $extra ) ? $extra : array() as $field ) { $ref = is_array( $field ) && is_string( $field['ref'] ?? null ) ? $field['ref'] : ''; if ( 0 !== strpos( $ref, 'meta:' ) || 'meta:' === $ref ) { continue; } $fields[] = array( 'ref' => $ref, 'label' => is_string( $field['label'] ?? null ) ? $field['label'] : $ref, 'group' => 'custom', 'description' => is_string( $field['description'] ?? null ) ? $field['description'] : '', ); } return $fields; } /** * Term-scope catalog entries (fixed set; no discovery needed). * * @return array */ private function termScopeFields(): array { return array( array( 'ref' => 'term:name', 'label' => __( 'Category name', 'ai-product-tools' ), 'group' => 'term', 'description' => __( 'The term name.', 'ai-product-tools' ) ), array( 'ref' => 'term:description', 'label' => __( 'Category description', 'ai-product-tools' ), 'group' => 'term', 'description' => __( 'The existing term description.', 'ai-product-tools' ) ), array( 'ref' => 'term:parent', 'label' => __( 'Parent category', 'ai-product-tools' ), 'group' => 'term', 'description' => __( 'The name of the parent term, if any.', 'ai-product-tools' ) ), array( 'ref' => 'term:children', 'label' => __( 'Subcategories', 'ai-product-tools' ), 'group' => 'term', 'description' => __( 'Names of direct child terms.', 'ai-product-tools' ) ), array( 'ref' => 'term:product_count', 'label' => __( 'Product count', 'ai-product-tools' ), 'group' => 'term', 'description' => __( 'How many products are assigned to this term.', 'ai-product-tools' ) ), array( 'ref' => 'term:top_products', 'label' => __( 'Top products', 'ai-product-tools' ), 'group' => 'term', 'description' => __( 'Names of a sample of products in this term.', 'ai-product-tools' ) ), array( 'ref' => 'term:common_attributes', 'label' => __( 'Common attributes', 'ai-product-tools' ), 'group' => 'term', 'description' => __( 'Attributes shared by most products in this term.', 'ai-product-tools' ) ), array( 'ref' => 'term:product_descriptions', 'label' => __( 'Product descriptions', 'ai-product-tools' ), 'group' => 'term', 'description' => __( 'The short descriptions of a sample of products in this term.', 'ai-product-tools' ) ), ); } /** * Image (attachment)-scope catalog entries (fixed set). * * @return array */ private function imageScopeFields(): array { return array( array( 'ref' => 'image:position', 'label' => __( 'Position', 'ai-product-tools' ), 'group' => 'image', 'description' => __( 'The 0-based position of this image among the product\'s images.', 'ai-product-tools' ) ), array( 'ref' => 'image:filename', 'label' => __( 'File name', 'ai-product-tools' ), 'group' => 'image', 'description' => __( 'The image file name.', 'ai-product-tools' ) ), array( 'ref' => 'image:title', 'label' => __( 'Title', 'ai-product-tools' ), 'group' => 'image', 'description' => __( 'The attachment title.', 'ai-product-tools' ) ), array( 'ref' => 'image:caption', 'label' => __( 'Caption', 'ai-product-tools' ), 'group' => 'image', 'description' => __( 'The attachment caption.', 'ai-product-tools' ) ), array( 'ref' => 'image:existing_alt', 'label' => __( 'Existing alt text', 'ai-product-tools' ), 'group' => 'image', 'description' => __( 'The alt text already saved for this image, if any.', 'ai-product-tools' ) ), ); } /** * Scope implied by a FieldRef's prefix. * * @param string $ref FieldRef. * @return string 'product' | 'term' | 'image' | '' (unknown prefix). */ private function scopeForRef( string $ref ): string { foreach ( array( 'core:', 'attr:', 'meta:' ) as $prefix ) { if ( 0 === strpos( $ref, $prefix ) ) { return 'product'; } } if ( 0 === strpos( $ref, 'term:' ) ) { return 'term'; } if ( 0 === strpos( $ref, 'image:' ) ) { return 'image'; } return ''; } /** * Discovered `attr:` refs: every global attribute taxonomy plus a * bounded sample of local (non-taxonomy) attribute names, mirroring * `CustomFields::get_product_attributes()`'s discovery approach. * * @return array Ref => label, insertion order preserved. */ private function productAttributeRefs(): array { $refs = array(); if ( function_exists( 'wc_get_attribute_taxonomies' ) ) { foreach ( (array) wc_get_attribute_taxonomies() as $attribute ) { if ( ! isset( $attribute->attribute_name ) ) { continue; } $name = (string) $attribute->attribute_name; $taxonomy = 'pa_' . $name; $ref = 'attr:' . $taxonomy; $label = ! empty( $attribute->attribute_label ) ? (string) $attribute->attribute_label : ( function_exists( 'wc_attribute_label' ) ? wc_attribute_label( $taxonomy ) : $name ); $refs[ $ref ] = $label; } } if ( function_exists( 'wc_get_products' ) ) { $products = (array) wc_get_products( array( 'limit' => self::ATTRIBUTE_SAMPLE_LIMIT, 'return' => 'objects', 'status' => array( 'publish', 'private', 'draft' ), ) ); foreach ( $products as $product ) { if ( ! $product instanceof WC_Product ) { continue; } foreach ( $product->get_attributes() as $name => $attribute ) { $ref = 'attr:' . $name; if ( isset( $refs[ $ref ] ) ) { continue; } if ( count( $refs ) >= self::ATTRIBUTE_NAME_LIMIT ) { break 2; } $refs[ $ref ] = function_exists( 'wc_attribute_label' ) ? wc_attribute_label( $name, $product ) : $name; } } } return $refs; } /** * @param string $value Plain text value. * @return array{type:string,value:string,empty:bool} */ private function text( string $value ): array { $value = $this->plain( $value ); return array( 'type' => 'text', 'value' => $value, 'empty' => ( '' === trim( $value ) ), ); } /** * @param string[] $values List of plain-text values. * @return array{type:string,value:string[],empty:bool} */ private function list( array $values ): array { $values = array_values( array_filter( $values, 'is_string' ) ); $values = array_map( array( $this, 'plain' ), $values ); $values = array_values( array_filter( $values, static function ( $value ) { return '' !== trim( $value ); } ) ); return array( 'type' => 'list', 'value' => $values, 'empty' => empty( $values ), ); } /** * @param array $pairs Label/value pairs. * @return array{type:string,value:array,empty:bool} */ private function pairs( array $pairs ): array { $result = array(); foreach ( $pairs as $pair ) { $value = $this->plain( (string) ( $pair['value'] ?? '' ) ); if ( '' === trim( $value ) ) { continue; } $result[] = array( 'label' => $this->plain( (string) ( $pair['label'] ?? '' ) ), 'value' => $value ); } return array( 'type' => 'pairs', 'value' => $result, 'empty' => empty( $result ), ); } /** * Store text as plain text. WordPress keeps term names HTML-encoded * ("Home & Living"), and content stripped of its tags still holds * entities ("30°C", " "); left alone they reach titles, meta * tags and prompts as literal entities. Every consumer escapes for its * own output (the renderer with esc_html(), prompts with escapeBlock()). * * @param string $value Store text. * @return string */ private function plain( string $value ): string { return str_replace( "\xC2\xA0", ' ', html_entity_decode( $value, ENT_QUOTES | ENT_HTML5, 'UTF-8' ) ); } /** * Price as plain text, with no HTML markup. * * @param mixed $raw_price Raw WooCommerce price value. * @return array{type:string,value:string,empty:bool} */ private function priceValue( $raw_price ): array { if ( null === $raw_price || '' === $raw_price ) { return $this->text( '' ); } if ( function_exists( 'wc_price' ) ) { $plain = html_entity_decode( wp_strip_all_tags( wc_price( $raw_price ) ), ENT_QUOTES | ENT_HTML5, 'UTF-8' ); return $this->text( trim( str_replace( "\xC2\xA0", ' ', $plain ) ) ); } return $this->text( (string) $raw_price ); } /** * @param WC_Product $product Product. * @param string $taxonomy 'product_cat' | 'product_tag'. * @return string[] */ private function productTermNames( WC_Product $product, string $taxonomy ): array { if ( ! function_exists( 'wp_get_post_terms' ) ) { return array(); } $terms = wp_get_post_terms( $product->get_id(), $taxonomy, array( 'fields' => 'names' ) ); return is_array( $terms ) ? array_values( array_map( 'strval', $terms ) ) : array(); } /** * This product's own category names, the store's default/placeholder * category (WooCommerce's "Uncategorized") left out: a product that was * never actually categorized carries that term like any real one, and * stating it as a fact reads as a real category to a merchant or an AI * prompt. Resolved by term id, the same identity * {@see \AIPT\Premium\ContentStructure\StoreSections\ComparisonContextBuilder::categoriesBySpecificity()} * already excludes it by, since a store can rename the default category * to anything. * * @param WC_Product $product Product. * @return string[] */ private function productCategoryNames( WC_Product $product ): array { if ( ! function_exists( 'wp_get_post_terms' ) ) { return array(); } $terms = wp_get_post_terms( $product->get_id(), 'product_cat', array( 'fields' => 'all' ) ); if ( ! is_array( $terms ) ) { return array(); } $names = array(); foreach ( $terms as $term ) { if ( $term instanceof WP_Term && ! ProductCategories::isDefault( (int) $term->term_id ) ) { $names[] = (string) $term->name; } } return $names; } /** * A grouped product's own child products, by name: the fact a bundle's * generated copy needs to say what it actually includes, which no other * core field carries (the only existing "*:children" ref is * `term:children`, for taxonomy subcategories). Only the children * shoppers see in the group ({@see ProductPrices::visibleGroupedChildren()}). * Empty for every other product type, including a grouped product with * no published children left. * * @param WC_Product $product Product. * @return string[] */ private function groupedChildProductNames( WC_Product $product ): array { if ( ! $product->is_type( 'grouped' ) || ! function_exists( 'wc_get_product' ) ) { return array(); } $names = array(); foreach ( ProductPrices::visibleGroupedChildren( $product ) as $child ) { $names[] = $child->get_name(); } return $names; } /** * The product's brand. WooCommerce Brands (the `product_brand` * taxonomy, core since WooCommerce 9.6) wins when it has terms for this * product; otherwise a Brand attribute, which `get_attribute( 'brand' )` * finds whether it is the global `pa_brand` taxonomy or a local * attribute named Brand. Empty when the store keeps brands in neither. * * @param WC_Product $product Product. * @return array{type:string,value:mixed,empty:bool} */ private function brandValue( WC_Product $product ): array { if ( function_exists( 'taxonomy_exists' ) && taxonomy_exists( 'product_brand' ) ) { $brands = $this->productTermNames( $product, 'product_brand' ); if ( ! empty( $brands ) ) { return $this->list( $brands ); } } return $this->text( $this->attributeValue( $product, 'brand' ) ); } /** * Weight with the store's configured unit, or '' when unset. * * @param WC_Product $product Product. * @return string */ private function weightText( WC_Product $product ): string { $weight = trim( (string) $product->get_weight() ); if ( '' === $weight ) { return ''; } $unit = trim( (string) get_option( 'woocommerce_weight_unit', '' ) ); return '' !== $unit ? $weight . ' ' . $unit : $weight; } /** * "L x W x H unit", omitting any dimension that is not set, or '' when * none are set. * * @param WC_Product $product Product. * @return string */ private function dimensionsText( WC_Product $product ): string { $parts = array_filter( array( trim( (string) $product->get_length() ), trim( (string) $product->get_width() ), trim( (string) $product->get_height() ), ), static function ( string $value ): bool { return '' !== $value; } ); if ( empty( $parts ) ) { return ''; } $unit = trim( (string) get_option( 'woocommerce_dimension_unit', '' ) ); $text = implode( ' x ', $parts ); return '' !== $unit ? $text . ' ' . $unit : $text; } /** * Every product attribute as label/value pairs (taxonomy and local). * * @param WC_Product $product Product. * @return array */ private function productAttributePairs( WC_Product $product ): array { $pairs = array(); foreach ( array_keys( (array) $product->get_attributes() ) as $name ) { $value = trim( wp_strip_all_tags( (string) $product->get_attribute( $name ) ) ); if ( '' === $value ) { continue; } $pairs[] = array( 'label' => $this->attributeLabelForProduct( $product, $name ), 'value' => $value, ); } return $pairs; } /** * A single attribute's label, resolved directly from THIS product * (`wc_attribute_label()`), falling back to the same ucwords()-based * heuristic when that resolves empty. Shared by `productAttributePairs()` * (the combined `core:attributes` field) and * `attributeRefLabelsForProduct()` (per-attribute Specifications rows) * so both label one attribute identically. * * @param WC_Product $product Product. * @param string $name Attribute key (e.g. 'pa_color' or a local slug). * @return string */ private function attributeLabelForProduct( WC_Product $product, string $name ): string { $label = function_exists( 'wc_attribute_label' ) ? wc_attribute_label( $name, $product ) : $name; $label = trim( wp_strip_all_tags( (string) $label ) ); if ( '' === $label ) { $label = ucwords( str_replace( array( 'pa_', '-', '_' ), array( '', ' ', ' ' ), (string) $name ) ); } return $label; } /** * A single attribute's value as plain text. * * @param WC_Product $product Product. * @param string $attribute_key Attribute key (e.g. 'pa_color' or a local slug). * @return string */ private function attributeValue( WC_Product $product, string $attribute_key ): string { return trim( wp_strip_all_tags( (string) $product->get_attribute( $attribute_key ) ) ); } /** * @param WP_Term $term Term. * @return string */ private function parentTermName( WP_Term $term ): string { if ( (int) $term->parent <= 0 || ! function_exists( 'get_term' ) ) { return ''; } $parent = get_term( $term->parent, $term->taxonomy ); return ( $parent instanceof WP_Term ) ? (string) $parent->name : ''; } /** * @param WP_Term $term Term. * @return string[] */ private function childTermNames( WP_Term $term ): array { if ( ! function_exists( 'get_terms' ) ) { return array(); } $children = get_terms( array( 'taxonomy' => $term->taxonomy, 'parent' => $term->term_id, 'hide_empty' => false, 'fields' => 'names', ) ); return is_array( $children ) ? array_values( array_map( 'strval', $children ) ) : array(); } /** * A bounded sample of product names assigned to this term, for any * product taxonomy the store uses (`product_cat`, `product_tag`, * `product_brand`, or another custom one) — not `product_cat` alone. * * @param WP_Term $term Term. * @return string[] */ private function topProductNames( WP_Term $term ): array { $products = TermProductSampler::sample( $term, array( 'limit' => self::TOP_PRODUCTS_LIMIT, 'orderby' => 'title', 'order' => 'ASC', ) ); $names = array(); foreach ( $products as $product ) { $names[] = $product->get_name(); } return $names; } }