1. I've custom post type called 'produkty'
  2. Inside this CPT I've taxonomy called 'kategorie_produktow' with terms (list of product categories, like in normal posts) - each product has ONE category
  3. Inside this CPT I've custom field called 'produkt_nowosc' - it is used to describe the product as newest in offer
  4. I'm using a custom page template to display all CPT with 'product_new' set as 'tak' (yes)

To display posts describe above I'm using normal WP_Query():

$the_query = new WP_Query( array( 'post_type' => 'produkty', 'meta_key' => 'produkt_nowosc', 'meta_value' => 'tak', 'posts_per_page' => -1) ) ;

It works perfect for displaying all products, with every product category (taxonomy and term). [product 1] [product 2] [product 3] [product 4]

Now I'd like to separate each CPT taxonomy, it's term and display posts with produkt_nowosc set to tak like this:

Post category 1:

[product 1] [product 2] [product 3]

Post category 2:

[product 4]

What type of query should I use?

  • You can try this approach. Just a note, this uses built in categories and the deafult posts, so you will need to modify the code accordingly – Pieter Goosen May 15 '15 at 7:55
  • 1
    Thank you Pieter! I've changed the code to matche the custom post type and taxonomies and voila! pastebin.com/xKBepGQz – knysha May 15 '15 at 8:13
  • You can post your code and what you did as an answer and accept your own answer. The are a badge for this as well :-) – Pieter Goosen May 15 '15 at 8:15
  • @PieterGoosen - oh, I didn't know that :) – knysha May 15 '15 at 8:43

Here's the code, rewriten from posts and categories to custom post types and taxonomy terms.

Thanks to @PieterGoosen for providing the first version.


$args = array(
    'post_type' => 'produkty', // your CTP name
    'meta_key' => 'produkt_nowosc', // custom meta key for displaying, in my case: the newest product in offer
    'meta_value' => 'tak', // field above set to 'yes'
    'posts_per_page' => -1

$query = new WP_Query($args);  
$q = array();

while ( $query->have_posts() ) {
    // displaying the content of product box etc.
    $a = '<a href="'. get_permalink() .'">' . get_the_title() .'</a>';
    $terms = wp_get_post_terms( $post->ID, 'kategorie_produktow', $args );
    foreach ( $terms as $term) {
        $term_link = get_term_link( $term );
        $b = '<span>'.$term->name.'</span>';    
    $q[$b][] = $a;
foreach ($q as $key=>$values) {
    echo $key;
    echo '<ul>';
        foreach ($values as $value){
            echo '<li>' . $value . '</li>';
    echo '</ul>';
  • +1 for posting your solution. You would want to have a look at transients as I have described in the linked answer as this can get quite expensive to run :-) – Pieter Goosen May 15 '15 at 9:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.