*/ function vasp_wc_catalog_get_brand_taxonomies(): array { $known = [ 'product_brand' => 10, 'pwb-brand' => 20, 'yith_product_brand' => 30, 'berocket_brand' => 40, 'pa_brand' => 50, ]; $taxonomies = []; foreach ($known as $taxonomy => $priority) { $object = get_taxonomy($taxonomy); if ($object) { $taxonomies[$taxonomy] = [ 'name' => $taxonomy, 'priority' => $priority, 'label' => $object->labels->name ?? $taxonomy, ]; } } $product_taxonomies = get_object_taxonomies('product', 'objects'); foreach ($product_taxonomies as $taxonomy => $object) { if (isset($taxonomies[$taxonomy]) || vasp_wc_catalog_is_non_brand_taxonomy($taxonomy)) { continue; } $haystack = strtolower($taxonomy . ' ' . ($object->labels->name ?? '') . ' ' . ($object->label ?? '')); if (strpos($haystack, 'brand') === false) { continue; } $taxonomies[$taxonomy] = [ 'name' => $taxonomy, 'priority' => 100, 'label' => $object->labels->name ?? $taxonomy, ]; } usort($taxonomies, static function ($left, $right) { if ($left['priority'] === $right['priority']) { return strcmp($left['name'], $right['name']); } return $left['priority'] <=> $right['priority']; }); return array_values($taxonomies); } /** * Return true for product taxonomies that are not brand sources. * * @param string $taxonomy Taxonomy slug. * @return bool */ function vasp_wc_catalog_is_non_brand_taxonomy(string $taxonomy): bool { return in_array($taxonomy, [ 'product_cat', 'product_tag', 'product_type', 'product_visibility', 'product_shipping_class', ], true); } /** * Return true when taxonomy is a supported brand taxonomy. * * @param string $taxonomy Taxonomy slug. * @return bool */ function vasp_wc_catalog_is_brand_taxonomy(string $taxonomy): bool { foreach (vasp_wc_catalog_get_brand_taxonomies() as $brand_taxonomy) { if (($brand_taxonomy['name'] ?? '') === $taxonomy) { return true; } } return false; } /** * Resolve one product or variation to the site's default-language object. * * Duplicate-post translation plugins expose one WordPress ID per language. * The catalog has one source owner, so only the object in the site's configured * default language may be synchronized. TranslatePress-style plugins that do * not duplicate posts naturally return the original ID. */ function vasp_wc_catalog_primary_product_id(int $product_id): int { if ($product_id <= 0) { return 0; } $post_type = get_post_type($product_id); if ($post_type !== 'product' && $post_type !== 'product_variation') { return 0; } $primary_id = $product_id; if (defined('ICL_SITEPRESS_VERSION')) { $default_language = (string) apply_filters('wpml_default_language', null); if ($default_language !== '') { $translated_id = apply_filters( 'wpml_object_id', $product_id, $post_type, false, $default_language ); $primary_id = $translated_id ? (int) $translated_id : 0; } } elseif (function_exists('pll_default_language') && function_exists('pll_get_post')) { $default_language = (string) pll_default_language('slug'); $translated_id = $default_language !== '' ? pll_get_post($product_id, $default_language) : false; $primary_id = $translated_id ? (int) $translated_id : 0; } /** * Allow another duplicate-post translation integration to identify its * default-language owner without making SKU a catalog identity. */ return max(0, (int) apply_filters( 'valuespace_catalog_primary_product_id', $primary_id, $product_id, $post_type )); } /** Return whether an ID is the single default-language catalog owner. */ function vasp_wc_catalog_product_id_is_primary(int $product_id): bool { return $product_id > 0 && vasp_wc_catalog_primary_product_id($product_id) === $product_id; } /** Keep only default-language product and variation IDs. */ function vasp_wc_catalog_primary_product_ids(array $product_ids): array { $primary_ids = []; foreach (array_values(array_unique(array_filter(array_map('intval', $product_ids)))) as $product_id) { if (vasp_wc_catalog_product_id_is_primary($product_id)) { $primary_ids[$product_id] = $product_id; } } return array_values($primary_ids); } /** * Build all brand payloads from detected brand taxonomies. * * @param array $brand_taxonomies Brand taxonomies. * @return array>|WP_Error */ function vasp_wc_catalog_get_all_brands(array $brand_taxonomies) { $brands = []; $seen = []; foreach ($brand_taxonomies as $brand_taxonomy) { $terms = get_terms([ 'taxonomy' => $brand_taxonomy['name'], 'hide_empty' => false, ]); if (is_wp_error($terms) || !is_array($terms)) { throw new RuntimeException('catalog_terms_read_failed'); } foreach (vasp_wc_catalog_filter_terms_for_published_products($terms, $brand_taxonomy['name']) as $term) { $key = vasp_wc_catalog_brand_dedupe_key($term); if (isset($seen[$key])) { continue; } $seen[$key] = true; $brand = vasp_wc_catalog_format_brand($term, $brand_taxonomy['name']); if (is_wp_error($brand)) { return $brand; } $brands[] = $brand; } } return $brands; } /** * Build category payloads. * * @return array>|WP_Error */ function vasp_wc_catalog_get_categories() { $terms = get_terms([ 'taxonomy' => 'product_cat', 'hide_empty' => false, ]); if (is_wp_error($terms) || !is_array($terms)) { throw new RuntimeException('catalog_terms_read_failed'); } $categories = []; foreach (vasp_wc_catalog_filter_terms_for_published_products($terms, 'product_cat') as $term) { $category = vasp_wc_catalog_format_category($term); if (is_wp_error($category)) { return $category; } $categories[] = $category; } return $categories; } /** * Build tag payloads. * * @return array> */ function vasp_wc_catalog_get_tags(): array { $terms = get_terms([ 'taxonomy' => 'product_tag', 'hide_empty' => false, ]); if (is_wp_error($terms) || !is_array($terms)) { throw new RuntimeException('catalog_terms_read_failed'); } return array_map('vasp_wc_catalog_format_tag', vasp_wc_catalog_filter_terms_for_published_products($terms, 'product_tag')); } /** * Build attribute payloads with terms. * * @return array> */ function vasp_wc_catalog_get_attributes(): array { global $wpdb; if (!function_exists('wc_get_attribute_taxonomies')) { return []; } $attribute_taxonomies = wc_get_attribute_taxonomies(); if ($wpdb->last_error !== '') { throw new RuntimeException('catalog_attributes_read_failed'); } if (empty($attribute_taxonomies) || !is_array($attribute_taxonomies)) { return []; } $attributes = []; foreach ($attribute_taxonomies as $attribute) { $taxonomy = wc_attribute_taxonomy_name($attribute->attribute_name); $terms = taxonomy_exists($taxonomy) ? get_terms([ 'taxonomy' => $taxonomy, 'hide_empty' => false, ]) : []; if (is_wp_error($terms) || !is_array($terms)) { throw new RuntimeException('catalog_terms_read_failed'); } $terms = vasp_wc_catalog_filter_terms_for_published_products($terms, $taxonomy); if (empty($terms)) { continue; } $attributes[] = [ 'externalId' => (string) $attribute->attribute_id, 'name' => $attribute->attribute_label ?: $attribute->attribute_name, 'slug' => $taxonomy, 'type' => $attribute->attribute_type ?? '', 'orderBy' => $attribute->attribute_orderby ?? '', 'hasArchives' => (bool) ($attribute->attribute_public ?? false), 'terms' => array_map('vasp_wc_catalog_format_attribute_term', $terms), ]; } return $attributes; } /** * Build product payloads from explicit WordPress storage fields. * * This reader is used by the high-volume catalog feed. It avoids WooCommerce * product object hydration and display/session filters by selecting only the * synchronized post, meta, term, and attachment fields needed for the payload. * * @param array $product_ids WooCommerce product or variation IDs. * @param array $brand_taxonomies Brand taxonomies. * @return array>|WP_Error */ function vasp_wc_catalog_get_product_payloads_from_storage(array $product_ids, array $brand_taxonomies) { $product_ids = vasp_wc_catalog_primary_product_ids($product_ids); if (empty($product_ids)) { return []; } $posts = vasp_wc_catalog_fetch_product_posts($product_ids); if (empty($posts)) { return []; } $parent_ids = []; foreach ($posts as $post) { if (($post['post_type'] ?? '') === 'product_variation') { $parent_id = (int) ($post['post_parent'] ?? 0); if ($parent_id > 0) { $parent_ids[$parent_id] = $parent_id; } } } $all_post_ids = array_values(array_unique(array_merge(array_keys($posts), array_values($parent_ids)))); $parent_posts = !empty($parent_ids) ? vasp_wc_catalog_fetch_product_posts(array_values($parent_ids)) : []; $posts += $parent_posts; $meta = vasp_wc_catalog_fetch_product_meta($all_post_ids); $term_taxonomies = array_merge( ['product_cat', 'product_tag', 'product_type', 'product_visibility'], array_map(static function ($brand_taxonomy) { return (string) ($brand_taxonomy['name'] ?? ''); }, $brand_taxonomies), vasp_wc_catalog_attribute_taxonomy_names() ); $terms = vasp_wc_catalog_fetch_product_terms($all_post_ids, $term_taxonomies); $variation_parent_ids = array_values($parent_ids); foreach ($product_ids as $product_id) { if (($posts[$product_id]['post_type'] ?? '') === 'product') { $variation_parent_ids[] = $product_id; } } $variation_ids_by_parent = vasp_wc_catalog_fetch_variation_ids_by_parent($variation_parent_ids); $attachments = vasp_wc_catalog_fetch_product_attachment_data($posts, $meta); $payloads = []; foreach ($product_ids as $product_id) { $post = $posts[$product_id] ?? null; if (!$post || ($post['post_status'] ?? '') !== 'publish') { continue; } $is_variation = ($post['post_type'] ?? '') === 'product_variation'; $parent_id = $is_variation ? (int) ($post['post_parent'] ?? 0) : 0; $parent_post = $parent_id > 0 ? ($posts[$parent_id] ?? null) : null; if ($is_variation && (!$parent_post || ($parent_post['post_status'] ?? '') !== 'publish')) { continue; } $base_id = $is_variation && $parent_id > 0 ? $parent_id : $product_id; $native_sku = vasp_wc_catalog_meta_string($meta, $product_id, '_sku'); $sku = vasp_wc_catalog_product_catalog_sku_from_storage($product_id, $native_sku, $base_id, $meta); $price = vasp_wc_catalog_meta_value($meta, $product_id, '_price'); $regular_price = vasp_wc_catalog_meta_value($meta, $product_id, '_regular_price'); $sale_price = vasp_wc_catalog_meta_value($meta, $product_id, '_sale_price'); $base_terms = $terms[$base_id] ?? []; $product_terms = $terms[$product_id] ?? []; $seller = vasp_wc_catalog_get_marketplace_seller($base_id); $images = vasp_wc_catalog_format_storage_images($product_id, $base_id, $meta, $attachments); if (is_wp_error($images)) { return $images; } $payloads[] = [ 'externalId' => (string) $product_id, 'sku' => $sku, 'slug' => (string) ($post['post_name'] ?? ''), 'name' => (string) ($post['post_title'] ?? ''), 'description' => wp_strip_all_tags((string) ($post['post_content'] ?? '')), 'shortDescription' => wp_strip_all_tags((string) ($post['post_excerpt'] ?? '')), 'link' => vasp_wc_catalog_product_link_from_storage($product_id, $base_id, $post, $parent_post), 'type' => $is_variation ? 'variation' : vasp_wc_catalog_product_type_from_terms($product_terms), 'status' => (string) ($post['post_status'] ?? ''), 'featured' => vasp_wc_catalog_terms_include_slug($base_terms, 'product_visibility', 'featured'), 'catalogVisibility' => vasp_wc_catalog_catalog_visibility_from_terms($base_terms), 'skuSource' => $native_sku === '' ? 'generated' : 'native', 'price' => vasp_wc_catalog_decimal($price), 'regularPrice' => vasp_wc_catalog_decimal($regular_price), 'salePrice' => vasp_wc_catalog_decimal($sale_price), 'onSale' => vasp_wc_catalog_product_is_on_sale_from_storage($price, $regular_price, $sale_price), 'purchasable' => vasp_wc_catalog_product_is_purchasable_from_storage($price), 'virtual' => vasp_wc_catalog_meta_bool($meta, $product_id, '_virtual'), 'downloadable' => vasp_wc_catalog_meta_bool($meta, $product_id, '_downloadable'), 'taxStatus' => vasp_wc_catalog_meta_string($meta, $product_id, '_tax_status'), 'taxClass' => vasp_wc_catalog_meta_string($meta, $product_id, '_tax_class'), 'manageStock' => vasp_wc_catalog_meta_bool($meta, $product_id, '_manage_stock'), 'stockQuantity' => vasp_wc_catalog_meta_nullable_number($meta, $product_id, '_stock'), 'stockStatus' => vasp_wc_catalog_meta_string($meta, $product_id, '_stock_status'), 'backorders' => vasp_wc_catalog_meta_string($meta, $product_id, '_backorders'), 'soldIndividually' => vasp_wc_catalog_meta_bool($meta, $product_id, '_sold_individually'), 'weight' => vasp_wc_catalog_decimal(vasp_wc_catalog_meta_value($meta, $product_id, '_weight')), 'dimensionLength' => vasp_wc_catalog_decimal_string(vasp_wc_catalog_meta_value($meta, $product_id, '_length')), 'dimensionWidth' => vasp_wc_catalog_decimal_string(vasp_wc_catalog_meta_value($meta, $product_id, '_width')), 'dimensionHeight' => vasp_wc_catalog_decimal_string(vasp_wc_catalog_meta_value($meta, $product_id, '_height')), 'reviewsAllowed' => (string) ($posts[$base_id]['comment_status'] ?? '') === 'open', 'averageRating' => vasp_wc_catalog_meta_string($meta, $base_id, '_wc_average_rating'), 'ratingCount' => (int) vasp_wc_catalog_meta_nullable_number($meta, $base_id, '_wc_review_count'), 'createdAt' => vasp_wc_catalog_storage_post_timestamp($post, 'created'), 'updatedAt' => vasp_wc_catalog_storage_post_timestamp($post, 'modified'), 'categories' => vasp_wc_catalog_format_storage_terms($base_terms, 'product_cat'), 'tags' => vasp_wc_catalog_format_storage_terms($base_terms, 'product_tag'), 'brands' => vasp_wc_catalog_format_storage_brand_terms($base_terms, $brand_taxonomies), 'attributes' => vasp_wc_catalog_format_storage_attributes($product_id, $base_id, $is_variation, $meta, $terms), 'images' => $images, 'upsellIds' => vasp_wc_catalog_filter_published_product_id_strings(vasp_wc_catalog_meta_id_list($meta, $base_id, '_upsell_ids')), 'crossSellIds' => vasp_wc_catalog_filter_published_product_id_strings(vasp_wc_catalog_meta_id_list($meta, $base_id, '_crosssell_ids')), 'variations' => !$is_variation ? array_map('strval', $variation_ids_by_parent[$product_id] ?? []) : [], 'parentExternalId' => $is_variation && $parent_id > 0 ? (string) $parent_id : null, 'sellerId' => $seller['id'], 'sellerName' => $seller['name'], 'sellerUrl' => $seller['url'], 'priceHtml' => vasp_wc_catalog_product_price_text($price, $regular_price, $sale_price), 'meta' => array_merge([ 'siteUrl' => home_url(), 'currency' => vasp_wc_catalog_base_currency(), ], vasp_wc_catalog_delivery_meta($product_id, $base_id, $meta)), ]; } return $payloads; } /** * Fetch product and variation post rows by ID. * * @param array $product_ids Product or variation IDs. * @return array> */ function vasp_wc_catalog_fetch_product_posts(array $product_ids): array { global $wpdb; $product_ids = array_values(array_unique(array_filter(array_map('intval', $product_ids)))); if (empty($product_ids)) { return []; } $placeholders = implode(',', array_fill(0, count($product_ids), '%d')); $rows = $wpdb->get_results($wpdb->prepare( "SELECT ID, post_author, post_parent, post_title, post_name, post_content, post_excerpt, post_status, post_type, post_date_gmt, post_modified_gmt, comment_status FROM %i WHERE ID IN ($placeholders) AND post_type IN ('product', 'product_variation')", array_merge([$wpdb->posts], $product_ids) ), ARRAY_A); if ($wpdb->last_error !== '' || !is_array($rows)) { throw new RuntimeException('catalog_source_read_failed'); } $posts = []; foreach (is_array($rows) ? $rows : [] as $row) { $posts[(int) $row['ID']] = $row; } return $posts; } /** * Fetch explicit product meta keys needed for catalog payloads. * * @param array $product_ids Product or variation IDs. * @return array> */ function vasp_wc_catalog_fetch_product_meta(array $product_ids): array { global $wpdb; $product_ids = array_values(array_unique(array_filter(array_map('intval', $product_ids)))); if (empty($product_ids)) { return []; } $meta_keys = [ '_sku', '_price', '_regular_price', '_sale_price', '_stock_status', '_manage_stock', '_stock', '_backorders', '_sold_individually', '_virtual', '_downloadable', '_tax_status', '_tax_class', '_weight', '_length', '_width', '_height', '_thumbnail_id', '_product_image_gallery', '_product_attributes', '_upsell_ids', '_crosssell_ids', '_wc_average_rating', '_wc_review_count', 'ships_in', 'shipping_time', 'delivery_time', ]; $id_placeholders = implode(',', array_fill(0, count($product_ids), '%d')); $key_placeholders = implode(',', array_fill(0, count($meta_keys), '%s')); $params = array_merge([$wpdb->postmeta], $product_ids, $meta_keys, [$wpdb->esc_like('attribute_') . '%']); $rows = $wpdb->get_results($wpdb->prepare( "SELECT post_id, meta_key, meta_value FROM %i WHERE post_id IN ($id_placeholders) AND (meta_key IN ($key_placeholders) OR meta_key LIKE %s)", $params ), ARRAY_A); if ($wpdb->last_error !== '' || !is_array($rows)) { throw new RuntimeException('catalog_source_read_failed'); } $meta = []; foreach (is_array($rows) ? $rows : [] as $row) { $post_id = (int) ($row['post_id'] ?? 0); $key = (string) ($row['meta_key'] ?? ''); if ($post_id <= 0 || $key === '') { continue; } $meta[$post_id][$key] = maybe_unserialize($row['meta_value']); } return $meta; } /** * Fetch product terms for selected taxonomies. * * @param array $product_ids Product or variation IDs. * @param array $taxonomies Taxonomy names. * @return array>>> */ function vasp_wc_catalog_fetch_product_terms(array $product_ids, array $taxonomies): array { global $wpdb; $product_ids = array_values(array_unique(array_filter(array_map('intval', $product_ids)))); $taxonomies = array_values(array_unique(array_filter(array_map('strval', $taxonomies)))); if (empty($product_ids) || empty($taxonomies)) { return []; } $id_placeholders = implode(',', array_fill(0, count($product_ids), '%d')); $taxonomy_placeholders = implode(',', array_fill(0, count($taxonomies), '%s')); $rows = $wpdb->get_results($wpdb->prepare( "SELECT tr.object_id, tt.taxonomy, t.term_id, t.name, t.slug FROM %i tr INNER JOIN %i tt ON tr.term_taxonomy_id = tt.term_taxonomy_id INNER JOIN %i t ON tt.term_id = t.term_id WHERE tr.object_id IN ($id_placeholders) AND tt.taxonomy IN ($taxonomy_placeholders) ORDER BY tt.taxonomy ASC, t.name ASC", array_merge([$wpdb->term_relationships, $wpdb->term_taxonomy, $wpdb->terms], $product_ids, $taxonomies) ), ARRAY_A); if ($wpdb->last_error !== '' || !is_array($rows)) { throw new RuntimeException('catalog_source_read_failed'); } $terms = []; foreach (is_array($rows) ? $rows : [] as $row) { $object_id = (int) ($row['object_id'] ?? 0); $taxonomy = (string) ($row['taxonomy'] ?? ''); if ($object_id <= 0 || $taxonomy === '') { continue; } $terms[$object_id][$taxonomy][] = [ 'externalId' => (string) ($row['term_id'] ?? ''), 'name' => (string) ($row['name'] ?? ''), 'slug' => (string) ($row['slug'] ?? ''), 'taxonomy' => $taxonomy, ]; } return $terms; } /** * Fetch published variation IDs grouped by parent. * * @param array $parent_ids Parent product IDs. * @return array> */ function vasp_wc_catalog_fetch_variation_ids_by_parent(array $parent_ids): array { global $wpdb; $parent_ids = array_values(array_unique(array_filter(array_map('intval', $parent_ids)))); if (empty($parent_ids)) { return []; } $placeholders = implode(',', array_fill(0, count($parent_ids), '%d')); $rows = $wpdb->get_results($wpdb->prepare( "SELECT ID, post_parent FROM %i WHERE post_parent IN ($placeholders) AND post_type = 'product_variation' AND post_status = 'publish' ORDER BY ID ASC", array_merge([$wpdb->posts], $parent_ids) ), ARRAY_A); if ($wpdb->last_error !== '' || !is_array($rows)) { throw new RuntimeException('catalog_source_read_failed'); } $variations = []; foreach (is_array($rows) ? $rows : [] as $row) { $parent_id = (int) ($row['post_parent'] ?? 0); $variation_id = (int) ($row['ID'] ?? 0); if ($parent_id > 0 && $variation_id > 0) { $variations[$parent_id][] = $variation_id; } } return $variations; } /** * Return product attribute taxonomy names. * * @return array */ function vasp_wc_catalog_attribute_taxonomy_names(): array { if (!function_exists('wc_get_attribute_taxonomies')) { return []; } $taxonomies = []; $attributes = wc_get_attribute_taxonomies(); foreach (is_array($attributes) ? $attributes : [] as $attribute) { $taxonomies[] = wc_attribute_taxonomy_name($attribute->attribute_name); } return array_values(array_filter(array_unique($taxonomies))); } /** * Read a scalar meta value. * * @param array> $meta Product meta map. * @param int $product_id Product ID. * @param string $key Meta key. * @return mixed */ function vasp_wc_catalog_meta_value(array $meta, int $product_id, string $key) { return $meta[$product_id][$key] ?? ''; } /** * Read a string meta value. * * @param array> $meta Product meta map. * @param int $product_id Product ID. * @param string $key Meta key. * @return string */ function vasp_wc_catalog_meta_string(array $meta, int $product_id, string $key): string { $value = vasp_wc_catalog_meta_value($meta, $product_id, $key); return is_scalar($value) ? (string) $value : ''; } /** Public delivery text only; variations inherit a missing estimate from their parent. */ function vasp_wc_catalog_delivery_meta(int $product_id, int $base_id, array $meta): array { $delivery = []; foreach (['ships_in', 'shipping_time', 'delivery_time'] as $key) { foreach (array_unique([$product_id, $base_id]) as $source_id) { $value = vasp_wc_catalog_meta_value($meta, $source_id, $key); if (!is_string($value)) { continue; } $value = trim(sanitize_text_field($value)); // Vesper's theme writes '-' when its ACF delivery field is empty. if ($value !== '' && $value !== '-') { $delivery[$key] = $value; break; } } } return $delivery; } /** * Read a WooCommerce yes/no meta value. * * @param array> $meta Product meta map. * @param int $product_id Product ID. * @param string $key Meta key. * @return bool */ function vasp_wc_catalog_meta_bool(array $meta, int $product_id, string $key): bool { return vasp_wc_catalog_meta_string($meta, $product_id, $key) === 'yes'; } /** * Read a nullable numeric meta value. * * @param array> $meta Product meta map. * @param int $product_id Product ID. * @param string $key Meta key. * @return int|float|null */ function vasp_wc_catalog_meta_nullable_number(array $meta, int $product_id, string $key) { $value = vasp_wc_catalog_meta_value($meta, $product_id, $key); if ($value === '' || $value === null || !is_numeric($value)) { return null; } return strpos((string) $value, '.') === false ? (int) $value : (float) $value; } /** * Read a meta list of product IDs. * * @param array> $meta Product meta map. * @param int $product_id Product ID. * @param string $key Meta key. * @return array */ function vasp_wc_catalog_meta_id_list(array $meta, int $product_id, string $key): array { $value = vasp_wc_catalog_meta_value($meta, $product_id, $key); if (is_string($value)) { $value = array_filter(array_map('trim', explode(',', $value))); } return is_array($value) ? array_values(array_filter(array_map('intval', $value))) : []; } /** * Return a unique SKU for catalog payloads built from storage. */ function vasp_wc_catalog_product_catalog_sku_from_storage(int $product_id, string $native_sku, int $base_id, array $meta): string { if ($native_sku !== '') { return $native_sku; } if ($base_id > 0 && $base_id !== $product_id) { $parent_sku = vasp_wc_catalog_meta_string($meta, $base_id, '_sku'); if ($parent_sku !== '') { return $parent_sku . '_' . $product_id; } } return 'wc-' . $product_id; } /** * Return a product permalink without using WooCommerce product objects. */ function vasp_wc_catalog_product_link_from_storage(int $product_id, int $base_id, array $post, ?array $parent_post): string { $link = get_permalink($product_id); if ($link || $product_id === $base_id) { return $link ?: ''; } return get_permalink($base_id) ?: ''; } /** * Return product type from product_type terms. * * @param array>> $terms Terms by taxonomy. */ function vasp_wc_catalog_product_type_from_terms(array $terms): string { $type_terms = $terms['product_type'] ?? []; return !empty($type_terms[0]['slug']) ? (string) $type_terms[0]['slug'] : 'simple'; } /** * Return true when a taxonomy term slug is assigned. * * @param array>> $terms Terms by taxonomy. */ function vasp_wc_catalog_terms_include_slug(array $terms, string $taxonomy, string $slug): bool { foreach ($terms[$taxonomy] ?? [] as $term) { if (($term['slug'] ?? '') === $slug) { return true; } } return false; } /** * Return WooCommerce catalog visibility from product_visibility terms. * * @param array>> $terms Terms by taxonomy. */ function vasp_wc_catalog_catalog_visibility_from_terms(array $terms): string { $hidden_catalog = vasp_wc_catalog_terms_include_slug($terms, 'product_visibility', 'exclude-from-catalog'); $hidden_search = vasp_wc_catalog_terms_include_slug($terms, 'product_visibility', 'exclude-from-search'); if ($hidden_catalog && $hidden_search) { return 'hidden'; } if ($hidden_catalog) { return 'search'; } if ($hidden_search) { return 'catalog'; } return 'visible'; } /** * Return whether stored price fields represent an active sale. */ function vasp_wc_catalog_product_is_on_sale_from_storage($price, $regular_price, $sale_price): bool { return $sale_price !== '' && $sale_price !== null && (string) $sale_price !== (string) $regular_price && (string) $price === (string) $sale_price; } /** * Return whether a product has enough stored data to be purchasable. */ function vasp_wc_catalog_product_is_purchasable_from_storage($price): bool { return $price !== '' && $price !== null; } /** * Format storage terms for product payloads. * * @param array>> $terms Terms by taxonomy. * @return array> */ function vasp_wc_catalog_format_storage_terms(array $terms, string $taxonomy): array { return array_map(static function ($term) { return [ 'externalId' => (string) ($term['externalId'] ?? ''), 'name' => (string) ($term['name'] ?? ''), 'slug' => (string) ($term['slug'] ?? ''), ]; }, $terms[$taxonomy] ?? []); } /** * Format storage brand terms for product payloads. * * @param array>> $terms Terms by taxonomy. * @param array $brand_taxonomies Brand taxonomies. * @return array> */ function vasp_wc_catalog_format_storage_brand_terms(array $terms, array $brand_taxonomies): array { $brands = []; $seen = []; foreach ($brand_taxonomies as $brand_taxonomy) { $taxonomy = (string) ($brand_taxonomy['name'] ?? ''); foreach ($terms[$taxonomy] ?? [] as $term) { $key = sanitize_title((string) (($term['slug'] ?? '') ?: ($term['name'] ?? ''))); if (isset($seen[$key])) { continue; } $seen[$key] = true; $brands[] = [ 'externalId' => (string) ($term['externalId'] ?? ''), 'name' => (string) ($term['name'] ?? ''), 'slug' => (string) ($term['slug'] ?? ''), 'link' => '', 'taxonomy' => $taxonomy, ]; } } return $brands; } /** * Format product attributes from stored meta and term assignments. * * @param array> $meta Product meta map. * @param array>>> $terms Terms by product and taxonomy. * @return array> */ function vasp_wc_catalog_format_storage_attributes(int $product_id, int $base_id, bool $is_variation, array $meta, array $terms): array { $attributes = []; if ($is_variation) { foreach ($meta[$product_id] ?? [] as $key => $value) { if (strpos((string) $key, 'attribute_') !== 0) { continue; } $slug = substr((string) $key, strlen('attribute_')); $attributes[] = [ 'name' => function_exists('wc_attribute_label') ? wc_attribute_label($slug) : $slug, 'slug' => $slug, 'options' => [wc_clean((string) $value)], 'visible' => true, 'variation' => true, ]; } return $attributes; } $definitions = vasp_wc_catalog_meta_value($meta, $base_id, '_product_attributes'); if (!is_array($definitions)) { return []; } foreach ($definitions as $definition) { if (!is_array($definition)) { continue; } $slug = (string) ($definition['name'] ?? ''); if ($slug === '') { continue; } $is_taxonomy = !empty($definition['is_taxonomy']); $options = []; if ($is_taxonomy) { foreach ($terms[$base_id][$slug] ?? [] as $term) { $options[] = (string) ($term['name'] ?? ''); } } else { $options = array_map('trim', explode('|', (string) ($definition['value'] ?? ''))); } $attributes[] = [ 'name' => function_exists('wc_attribute_label') ? wc_attribute_label($slug) : $slug, 'slug' => $slug, 'options' => array_values(array_filter(array_map('strval', $options), 'strlen')), 'visible' => !empty($definition['is_visible']), 'variation' => !empty($definition['is_variation']), ]; } return $attributes; } /** * Fetch attachment data needed by product images. * * @param array> $posts Product posts. * @param array> $meta Product meta map. * @return array> */ function vasp_wc_catalog_fetch_product_attachment_data(array $posts, array $meta): array { $attachment_ids = []; foreach ($posts as $product_id => $post) { $thumbnail_id = (int) vasp_wc_catalog_meta_value($meta, (int) $product_id, '_thumbnail_id'); if ($thumbnail_id > 0) { $attachment_ids[$thumbnail_id] = $thumbnail_id; } foreach (array_filter(array_map('intval', explode(',', vasp_wc_catalog_meta_string($meta, (int) $product_id, '_product_image_gallery')))) as $gallery_id) { if ($gallery_id > 0) { $attachment_ids[$gallery_id] = $gallery_id; } } } if (empty($attachment_ids)) { return []; } $ids = array_values($attachment_ids); if (function_exists('_prime_post_caches')) { _prime_post_caches($ids, false, true); } $attachments = []; foreach ($ids as $attachment_id) { $src = vasp_wc_catalog_image_url($attachment_id); if ($src === '') { continue; } $attachments[$attachment_id] = [ 'src' => $src, 'name' => (string) get_the_title($attachment_id), 'alt' => (string) get_post_meta($attachment_id, '_wp_attachment_image_alt', true), 'sourceRevision' => vasp_wc_catalog_image_source_revision($attachment_id), ]; } return $attachments; } /** * Format images from selected attachment data. * * @param array> $meta Product meta map. * @param array> $attachments Attachment data. * @return array> */ function vasp_wc_catalog_ordered_image_ids(int $product_id, int $base_id, array $meta): array { $thumbnail_id = (int) vasp_wc_catalog_meta_value($meta, $product_id, '_thumbnail_id'); if ($thumbnail_id <= 0 && $product_id !== $base_id) { $thumbnail_id = (int) vasp_wc_catalog_meta_value($meta, $base_id, '_thumbnail_id'); } $image_ids = []; if ($thumbnail_id > 0) { $image_ids[] = $thumbnail_id; } foreach (array_filter(array_map('intval', explode(',', vasp_wc_catalog_meta_string($meta, $base_id, '_product_image_gallery')))) as $gallery_id) { if ($gallery_id > 0 && !in_array($gallery_id, $image_ids, true)) { $image_ids[] = $gallery_id; } } return $image_ids; } /** Return the public source URL required by product JSON and binary delivery. */ function vasp_wc_catalog_image_url(int $attachment_id): string { $src = wp_get_attachment_url($attachment_id); return is_string($src) ? $src : ''; } /** Keep only image IDs that can be represented in both product JSON and binary delivery. */ function vasp_wc_catalog_deliverable_image_ids( int $product_id, int $base_id, array $meta, ?array $attachments = null ): array { return array_values(array_filter( vasp_wc_catalog_ordered_image_ids($product_id, $base_id, $meta), static function (int $attachment_id) use ($attachments): bool { $src = $attachments === null ? vasp_wc_catalog_image_url($attachment_id) : ($attachments[$attachment_id]['src'] ?? ''); return is_string($src) && $src !== ''; } )); } function vasp_wc_catalog_format_storage_images(int $product_id, int $base_id, array $meta, array $attachments) { $configured_image_ids = vasp_wc_catalog_ordered_image_ids($product_id, $base_id, $meta); $image_ids = vasp_wc_catalog_deliverable_image_ids($product_id, $base_id, $meta, $attachments); if (count($image_ids) !== count($configured_image_ids)) { $resolved = array_fill_keys($image_ids, true); foreach ($configured_image_ids as $attachment_id) { if (!isset($resolved[$attachment_id])) { return vasp_wc_catalog_unresolved_image_error($attachment_id, $product_id); } } } $images = []; foreach ($image_ids as $position => $attachment_id) { $attachment = $attachments[$attachment_id] ?? null; if (!is_array($attachment) || trim((string) ($attachment['src'] ?? '')) === '') { return vasp_wc_catalog_unresolved_image_error($attachment_id, $product_id); } $src = (string) ($attachment['src'] ?? ''); $images[] = [ 'id' => (string) $attachment_id, 'src' => $src, 'name' => (string) ($attachment['name'] ?? ''), 'alt' => (string) ($attachment['alt'] ?? ''), 'position' => $position, 'sourceRevision' => (string) ($attachment['sourceRevision'] ?? ''), ]; } return $images; } /** * Format a post timestamp from selected post rows. */ function vasp_wc_catalog_storage_post_timestamp(array $post, string $field): ?string { $key = $field === 'modified' ? 'post_modified_gmt' : 'post_date_gmt'; $value = (string) ($post[$key] ?? ''); if ($value === '' || $value === '0000-00-00 00:00:00') { return null; } $timestamp = strtotime($value . ' UTC'); return is_int($timestamp) ? gmdate('c', $timestamp) : null; } /** Cache source membership once per snapshot request without hydrating products. */ function vasp_wc_catalog_published_product_ids(): array { global $wpdb; static $product_ids = null; if ($product_ids !== null) { return $product_ids; } $ids = wc_get_products(['status' => ['publish'], 'limit' => -1, 'return' => 'ids']); if ($wpdb->last_error !== '' || !is_array($ids)) { throw new RuntimeException('catalog_scope_read_failed'); } $product_ids = array_values(array_unique(array_filter(array_map('intval', $ids)))); return $product_ids; } /** * Return published term IDs and counts for one taxonomy without hydrating every product. * * @param string $taxonomy Taxonomy slug. * @return array{term_ids:array,term_counts:array} */ function vasp_wc_catalog_get_published_taxonomy_scope(string $taxonomy): array { global $wpdb; static $scopes = []; if (isset($scopes[$taxonomy])) { return $scopes[$taxonomy]; } $product_ids = vasp_wc_catalog_published_product_ids(); $term_ids = []; $term_counts = []; if (empty($product_ids) || !taxonomy_exists($taxonomy)) { $scopes[$taxonomy] = [ 'term_ids' => [], 'term_counts' => [], ]; return $scopes[$taxonomy]; } foreach (array_chunk($product_ids, 500) as $product_id_chunk) { $placeholders = implode(',', array_fill(0, count($product_id_chunk), '%d')); $rows = $wpdb->get_results($wpdb->prepare(" SELECT tt.term_id, COUNT(DISTINCT tr.object_id) AS product_count FROM %i tr INNER JOIN %i tt ON tr.term_taxonomy_id = tt.term_taxonomy_id WHERE tt.taxonomy = %s AND tr.object_id IN ($placeholders) GROUP BY tt.term_id ", array_merge([$wpdb->term_relationships, $wpdb->term_taxonomy, $taxonomy], $product_id_chunk) ), ARRAY_A); if ($wpdb->last_error !== '' || !is_array($rows)) { throw new RuntimeException('catalog_source_read_failed'); } foreach ($rows as $row) { $term_id = (int) ($row['term_id'] ?? 0); $count = (int) ($row['product_count'] ?? 0); if ($term_id <= 0 || $count <= 0) { continue; } $visible_ids = [$term_id]; foreach (get_ancestors($term_id, $taxonomy, 'taxonomy') as $ancestor_id) { $visible_ids[] = (int) $ancestor_id; } foreach (array_values(array_unique($visible_ids)) as $visible_id) { if ($visible_id <= 0) { continue; } $term_ids[$visible_id] = $visible_id; $term_counts[$visible_id] = ($term_counts[$visible_id] ?? 0) + $count; } } } $scopes[$taxonomy] = [ 'term_ids' => array_values($term_ids), 'term_counts' => $term_counts, ]; return $scopes[$taxonomy]; } /** * Return whether a WooCommerce product should exist in ValueSpace catalog. * * @param WC_Product $product Product instance. * @return bool */ function vasp_wc_catalog_product_is_published(WC_Product $product): bool { return $product->get_status() === 'publish'; } /** * Filter terms to those used by published products. * * @param array $terms Terms returned by WordPress. * @param string $taxonomy Taxonomy slug. * @return array */ function vasp_wc_catalog_filter_terms_for_published_products(array $terms, string $taxonomy): array { $scope = vasp_wc_catalog_get_published_taxonomy_scope($taxonomy); $term_ids = array_fill_keys($scope['term_ids'], true); return array_values(array_filter($terms, static function ($term) use ($term_ids) { return $term instanceof WP_Term && isset($term_ids[(int) $term->term_id]); })); } /** * Return optional Dokan seller identity for a marketplace product. * * Ordinary WooCommerce stores deliberately return empty values: a WordPress * post author is not automatically a marketplace seller. * * @param int $product_id Parent product ID. * @return array{id:string,name:string,url:string} */ function vasp_wc_catalog_get_marketplace_seller(int $product_id): array { static $cache = []; if (isset($cache[$product_id])) { return $cache[$product_id]; } $empty = ['id' => '', 'name' => '', 'url' => '']; if ($product_id <= 0 || !function_exists('dokan_get_vendor_by_product')) { $cache[$product_id] = $empty; return $empty; } $vendor = dokan_get_vendor_by_product($product_id); if (!is_object($vendor)) { $cache[$product_id] = $empty; return $empty; } $id = method_exists($vendor, 'get_id') ? (int) $vendor->get_id() : 0; $name = method_exists($vendor, 'get_shop_name') ? (string) $vendor->get_shop_name() : ''; $url = method_exists($vendor, 'get_shop_url') ? (string) $vendor->get_shop_url() : ''; $cache[$product_id] = [ 'id' => $id > 0 ? (string) $id : '', 'name' => trim($name), 'url' => esc_url_raw($url), ]; return $cache[$product_id]; } /** * Return the store's base WooCommerce currency, not a request/session override. * * @return string */ function vasp_wc_catalog_base_currency(): string { $currency = (string) get_option('woocommerce_currency', ''); return $currency !== '' ? $currency : get_woocommerce_currency(); } /** * Return stable price text for catalog payloads. * * @param mixed $price Current stored product price. * @param mixed $regular_price Stored regular price. * @param mixed $sale_price Stored sale price. * @return string */ function vasp_wc_catalog_product_price_text($price, $regular_price, $sale_price): string { $price = vasp_wc_catalog_decimal_string($price); $regular_price = vasp_wc_catalog_decimal_string($regular_price); $sale_price = vasp_wc_catalog_decimal_string($sale_price); if ($sale_price !== null && $regular_price !== null && $sale_price !== $regular_price) { return $regular_price . ' -> ' . $sale_price; } return $price ?? ''; } /** * Return stable published product ID strings. * * @param array $product_ids Product IDs. * @return array */ function vasp_wc_catalog_filter_published_product_id_strings(array $product_ids): array { $published = []; foreach (array_unique(array_filter(array_map('intval', $product_ids))) as $product_id) { if (vasp_wc_catalog_product_id_is_published($product_id)) { $published[] = $product_id; } } sort($published, SORT_NUMERIC); return array_map('strval', $published); } /** * Return whether a product ID points to published product catalog data. * * @param int $product_id Product or variation ID. * @return bool */ function vasp_wc_catalog_product_id_is_published(int $product_id): bool { if ($product_id <= 0 || get_post_status($product_id) !== 'publish' || !vasp_wc_catalog_product_id_is_primary($product_id)) { return false; } $post_type = get_post_type($product_id); if ($post_type === 'product') { return true; } $parent_id = wp_get_post_parent_id($product_id); return $post_type === 'product_variation' && get_post_type($parent_id) === 'product' && get_post_status($parent_id) === 'publish' && vasp_wc_catalog_product_id_is_primary($parent_id); } /** * Count published products attached to a taxonomy term. * * @param WP_Term $term Taxonomy term. * @param string $taxonomy Taxonomy slug. * @return int */ function vasp_wc_catalog_published_term_count(WP_Term $term, string $taxonomy): int { $scope = vasp_wc_catalog_get_published_taxonomy_scope($taxonomy); return (int) ($scope['term_counts'][(int) $term->term_id] ?? 0); } /** * Format one brand term. * * @param WP_Term $term Brand term. * @param string $taxonomy Taxonomy slug. * @return array|WP_Error */ function vasp_wc_catalog_format_brand(WP_Term $term, string $taxonomy) { $thumbnail_id = (int) get_term_meta($term->term_id, 'thumbnail_id', true); $image = $thumbnail_id > 0 ? vasp_wc_catalog_format_image($thumbnail_id, 0) : null; if (is_wp_error($image)) { return $image; } return [ 'externalId' => (string) $term->term_id, 'name' => $term->name, 'slug' => $term->slug, 'parentExternalId' => $term->parent > 0 ? (string) $term->parent : null, 'description' => wp_strip_all_tags($term->description), 'shortDescription' => '', 'display' => $taxonomy, 'image' => $image, 'menuOrder' => 0, 'count' => vasp_wc_catalog_published_term_count($term, $taxonomy), 'link' => vasp_wc_catalog_term_link($term), 'taxonomy' => $taxonomy, ]; } /** * Format one category term. * * @param WP_Term $term Category term. * @return array|WP_Error */ function vasp_wc_catalog_format_category(WP_Term $term) { $thumbnail_id = (int) get_term_meta($term->term_id, 'thumbnail_id', true); $image = $thumbnail_id > 0 ? vasp_wc_catalog_format_image($thumbnail_id, 0) : null; if (is_wp_error($image)) { return $image; } return [ 'externalId' => (string) $term->term_id, 'name' => $term->name, 'slug' => $term->slug, 'parentExternalId' => $term->parent > 0 ? (string) $term->parent : null, 'description' => wp_strip_all_tags($term->description), 'display' => '', 'image' => $image, 'menuOrder' => 0, 'count' => vasp_wc_catalog_published_term_count($term, 'product_cat'), ]; } /** * Format one product tag term. * * @param WP_Term $term Tag term. * @return array */ function vasp_wc_catalog_format_tag(WP_Term $term): array { return [ 'externalId' => (string) $term->term_id, 'name' => $term->name, 'slug' => $term->slug, 'description' => wp_strip_all_tags($term->description), 'count' => vasp_wc_catalog_published_term_count($term, 'product_tag'), ]; } /** * Format one attribute term. * * @param WP_Term $term Attribute term. * @return array */ function vasp_wc_catalog_format_attribute_term(WP_Term $term): array { return [ 'externalId' => (string) $term->term_id, 'name' => $term->name, 'slug' => $term->slug, 'description' => wp_strip_all_tags($term->description), 'menuOrder' => 0, 'count' => vasp_wc_catalog_published_term_count($term, $term->taxonomy), ]; } /** * Format one WordPress attachment image. * * @param int $attachment_id Attachment ID. * @param int $position Display position. * @return array|WP_Error */ function vasp_wc_catalog_format_image(int $attachment_id, int $position) { $url = wp_get_attachment_url($attachment_id); if (empty($url)) { return vasp_wc_catalog_unresolved_image_error($attachment_id); } $image = [ 'id' => (string) $attachment_id, 'src' => $url, 'name' => (string) get_the_title($attachment_id), 'alt' => get_post_meta($attachment_id, '_wp_attachment_image_alt', true), 'position' => $position, 'sourceRevision' => vasp_wc_catalog_image_source_revision($attachment_id), ]; return $image; } /** Keep a configured owner intact until its attachment source can be read again. */ function vasp_wc_catalog_unresolved_image_error(int $attachment_id, int $product_id = 0): WP_Error { $vasp_product_ids = $product_id > 0 ? [$product_id] : []; return vasp_wc_catalog_storage_error('image_source_missing', [ 'error_code' => 'image_source_missing', 'step' => 'catalog_payload', 'image_file' => (string) $attachment_id, 'image_ids' => [$attachment_id], 'product_ids' => $vasp_product_ids, // A missing configured Media Library source needs administrator action. // Treating it as transient retries the same product packet forever. 'can_retry' => $product_id <= 0, ]); } /** Return the same UTC modification revision exposed by WooCommerce REST. */ function vasp_wc_catalog_image_source_revision(int $attachment_id): string { $modified_gmt = (string) get_post_field('post_modified_gmt', $attachment_id); if ($modified_gmt === '' || $modified_gmt === '0000-00-00 00:00:00') { return ''; } $timestamp = DateTimeImmutable::createFromFormat( '!Y-m-d H:i:s', $modified_gmt, new DateTimeZone('UTC') ); if (!$timestamp instanceof DateTimeImmutable) { return ''; } return 'wp-modified-v1:' . hash('sha256', $timestamp->format('Y-m-d\TH:i:s.0000000\Z')); } /** * Deduplicate matching brands across plugins by normalized slug/name. * * @param WP_Term $term Brand term. * @return string */ function vasp_wc_catalog_brand_dedupe_key(WP_Term $term): string { $value = !empty($term->slug) ? $term->slug : $term->name; return sanitize_title($value); } /** * Return a term permalink or an empty string when unavailable. * * @param WP_Term $term Term. * @return string */ function vasp_wc_catalog_term_link(WP_Term $term): string { $link = get_term_link($term); return is_wp_error($link) ? '' : (string) $link; } /** * Normalize WooCommerce decimal values for JSON payloads. * * @param mixed $value Decimal-ish value. * @return float|null */ function vasp_wc_catalog_decimal($value): ?float { if ($value === '' || $value === null) { return null; } return (float) $value; } /** * Normalize WooCommerce decimal values for string-valued catalog fields. * * Product dimensions are string fields in the Gateway contract because * WooCommerce stores them as display-oriented values. * * @param mixed $value Decimal-ish value. * @return string|null */ function vasp_wc_catalog_decimal_string($value): ?string { if ($value === '' || $value === null) { return null; } return (string) $value; }