Search code examples
phpwordpresscategoriesposts

Query posts outputs news items 5 times


I have a problem retreiving posts into a page. I try to get posts of a specific category but when the posts get loaded they get displayed 5 times. I allready tried to change the number of posts to view in the admin panel but this doesn't have effect on the output of the posts.

This is my code:

<div id="primary" class="content-area">
    <main id="main" class="site-main" role="main">

        <?php

        query_posts( array ( 'category_name' => 'nieuwsitem', 'posts_per_page' => 20 ) );

         while ( have_posts() ) : the_post(); ?>

        <?php $myposts = get_posts('');
              foreach($myposts as $post) :
              setup_postdata($post);
              ?>
                <div class="post-item">
                  <div class="thedate"><?php echo get_the_time('d/m/Y', $post->ID); ?></p></div>
                  <div class="post-info">
                    <h2 class="post-title">
                    <a href="<?php the_permalink() ?>" title="<?php the_title_attribute(); ?>">
                    <?php the_title(); ?>
                    </a>
                    </h2>
                  </div>
                  <div class="post-content">
                  <?php the_content(); ?>
                  </div>
                </div>
              <?php endforeach; wp_reset_postdata(); ?>

        <?php endwhile; // end of the loop. ?>

    </main><!-- #main -->
</div><!-- #primary -->

Thanks in advance!


Solution

  • You've created 2 loops. Removing the foreach part of your code should fix this:

    <div id="primary" class="content-area">
    <main id="main" class="site-main" role="main">
    
        <?php
    
        query_posts( array ( 'category_name' => 'nieuwsitem', 'posts_per_page' => 20 ) );
    
         while ( have_posts() ) : the_post(); ?>
    
                <div class="post-item">
                  <div class="thedate"><?php echo get_the_time('d/m/Y', $post->ID); ?></p></div>
                  <div class="post-info">
                    <h2 class="post-title">
                    <a href="<?php the_permalink() ?>" title="<?php the_title_attribute(); ?>">
                    <?php the_title(); ?>
                    </a>
                    </h2>
                  </div>
                  <div class="post-content">
                  <?php the_content(); ?>
                  </div>
                </div>
    
        <?php endwhile; // end of the loop. ?>
    
    </main><!-- #main -->