Search code examples
wordpressgetposts

Wordpress - How do I show only the 4 newest posts on my page?


I am trying to only load the 4 latest posts on my page and I have found a line of code that should work. The problem is that I don't know where to put it.

<?php query_posts('posts_per_page=20'); ?>

This is what I found when I was searching for a solution (although I don't know if this will also work for showing only the 4 newest posts. As you can see I already have 'catname=projecten' on that line and I have no idea how to combine the two.

<?php
query_posts('catname=projecten');
while (have_posts()) : the_post();?>
<div class="col-md-3">
  <div class="newsfeed center">
    <h1><?php echo get_the_title( $ID ); ?> </h1>
    <p>
<?php the_content(); ?>
      </p>
  </div>
</div>
<?php endwhile;
?>

I hope someone can help me out!


Solution

  • I'd like to answer it, because there are few things need to be corrected. This should do it, and notes below.

    <?php
    query_posts('category_name=projecten&posts_per_page=4');
    while (have_posts()) : the_post(); ?>
    <div class="col-md-3">
      <div class="newsfeed center">
        <h2><?php echo get_the_title(); ?> </h2>
        <?php the_content(); ?>
      </div>
    </div>
    <?php endwhile; wp_reset_query(); ?>
    

    A few notes:

    • It's category_name, not catname.

    • You should not use <h1> for each title, for a better accessibility use <h2> or <h3> etc.

    • get_the_title( $ID ); the $ID seems not necessary to be there.

    • Don't wrap the_content(); with <p> it's rich content already, use <div> if you need.

    • Don't forget to reset the query afterwards.

    http://codex.wordpress.org/Class_Reference/WP_Query#Category_Parameters

    http://codex.wordpress.org/Function_Reference/query_posts

    http://codex.wordpress.org/Class_Reference/WP_Query