I was trying to perform a query between two WordPress Taxonomies. The taxonomies I would be using are brand and product_cat.
The expected result is to display in a Dropdown all existing Brands as Fathers and all the existing product categories of each brand has as children*
What I tried at first was to iterate over all products asking for their categories and their brands, forming an associative array; but this ended on PHP Fatal error: Allowed memory size of 268435456 bytes exhausted as they are 10 000 products in the database. This was the code I used:
<?php
$args = array(
'posts_per_page' => 25,
'post_type' => 'product',
);
$relations = array();
$loop = new WP_Query($args);
if ($loop->have_posts()) {
while ($loop->have_posts()) {
$loop->the_post();
$productBrandTerm = get_field('brand');
$productCategory = wp_get_post_terms(get_the_ID(), 'product_cat', $catArgs);
if ($productBrandTerm) {
if ($relations[$productBrandTerm->slug]) {
array_push($relations[$productBrandTerm->slug], $productCategory[0]->name);
$relations[$productBrandTerm->slug] = array_unique($relations[$productBrandTerm->slug]);
} else {
$relations[$productBrandTerm->slug] = array($productCategory[0]->name);
}
}
}
} else {
echo "____";
}
wp_reset_postdata();
foreach ($relations as $key => $value) {
echo '<p class="menu_marcas" id="' . $key . '">';
echo $key;
echo '</p>';
echo '<div class="menu_categorias">';
foreach ($value as $k) {
echo '<a href="#">';
echo $k;
echo '</a>';
}
echo '</div><!-- menu_categorias --> ';
}
?>
When I say "existing brand" I mean the Categories that at least have one product.
I don't know if there is an optimal way to achieve this with WP_Query, or with raw SQL, in any case, which would it be the optimal way to do it?
EDIT: I forgot to mention this productBrandTerm is an Advanced Custom Field ACF field working as Product Taxonomy, which displays as an attribute of WooCommerce products. That is why I call it via get_field and ask for its slug.