Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

WordPress

WP_Query loop duplicates posts by the numbers of posts (3 posts = 9)

I'm hoping there is a clever person out there who can tell me why this WP_Query loops display way to many posts.

I have 3 posts and it loops through and display each posts 3 times (duplicates). If I had 4 posts it will output the same post 4 times. You get the idea. My thought was to put an endif and endwhile in the loop, but it throws and unexpected statement error.

Can anyone solve this?

<?php

$args = array(
    'post_type' => 'projects'
);

// the WP_Query
$project = new WP_Query( $args );

if ( $project->have_posts() ) {
    // start the loop
    while ( $project->have_posts() ) {
        $project->the_post();
        $terms = get_the_terms( $post->ID, 'typologi' );

        // since get_the_terms returns WP_Term and only the slugs are needed
        $terms_only_slugs = array_map( function( $term ) {
        return $term->slug;
        }, $terms );

        // when multiple terms set make it a string
        $element_item_classes = implode( ' ', $terms_only_slugs );

        // pass the string as an attribute
        echo '<div class="element-item ' . $element_item_classes . '">';

        the_post_thumbnail( array(600, 600) ); // size: 600x600px
        the_title( sprintf( '<h3 class="item-title"><a href="%s" rel="bookmark">', esc_url( get_permalink() ) ), '</a></h3>' ); ?>
        <h5><?php echo get_the_term_list( $post->ID, 'typologi', 'Typologi: ', '', '' ); ?></h5><?php

        echo '</div>';
    }
}
wp_reset_postdata();
?>

1 Answer

Kevin Korte
Kevin Korte
28,149 Points

mmm...I don't have all of the meta data you do, but I boiled your code down to just the loop, and it didn't repeat itself, it pulled in exactly one, so I'll have to read through this again

I can provide additional information or metadata, just tell me what you think you need. Or have any other questions. I'm clueless myself.