I have a "brand" page (ex. Nike). When I click on "Nike" page I would like to show a list of all categories of their products (ex. shoes, thirts ecc). Each category of their products is listed by a random item of that category. I want that everytime a reload the page "Nike", the category "Shoes" will show a different model of Shoe in a random way. But I want that all categories al sorted alphabetically.
Consider this: - "tipo_prodotto" (product_type) is a custom field. - "brand" is a custom field too, is a relation with "Brand" custom post type. - "tipo_pagina" is a custom field.
Pages are organized in this way - Macro Area (ex. Shoes) -- Categora (Female Shoes, Male Shoes, Kids Shoes) --- Sub Categoria (ex. Running Shoes, Trekking Shoes) ---- Product (ex. Nike Air Jordan, Nike 2, Nike 3)
tipo_pagina can ben 'macroarea','category','subcagetory','prodotto'
So the query request all products by a brand randomly.
The WP_Query for now is this one:
$args = array( 'posts_per_page' => -1, 'post_type' => 'page', 'post_status' => 'publish', 'orderby' => 'tipo_prodotto', 'order' => 'rand', 'meta_query' => array( 'relation' => 'AND', array( 'key' => 'tipo_pagina', 'value' => 'prodotto', 'compare' => '=' ), array( 'key' => 'brand', 'value' => get_the_id(), 'compare' => 'LIKE', ), ) ); // query $the_query = new WP_Query( $args );
The problem is that ok, a random item is listed every time of each category, but the categories are sorted randomly too.
After the query, in the loop I check if a product of a certain category has been already shown, so I skip it and I show just one product for each category.
if(!in_array(get_field('tipo_prodotto'), $current_tipo_prodotto)): $thumb_to_show=get_the_post_thumbnail(NULL, 'thumbnail', array( 'class' => 'child-thumb' )); array_push($current_tipo_prodotto, get_field('tipo_prodotto')); // load the category to link $post=get_post(); while(get_field('tipo_pagina', $post->post_parent)!='macro-area'): $post=get_post($post->post_parent); endwhile;
I have two questions: - How can I sort the categories alphabetically? - How can I tell the query that I want just ONE random product of each category so I can avoid to do the if statement above?
I thought the I should use the get_posts to have an array of all posts and sort it, the number of products of each category are of 7-8 max, so I don't thinks it very memory expensive make this, but I think is not a very elegant way. ??
I hope I have explained well enough the problem and please, be merciful with judging the code I wrote. I'm a improvised developer.