1
votes

This is my code from to get posts from category 1:

<?php query_posts('cat=1'); ?>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

    <h2><?php the_title(); ?></h2>

<?php endwhile; endif; ?>

but I have 3 blog posts and it is display all 3 blog posts title. i want it to only display 1 blog post. how can i do that in the while loop? thanks

2

2 Answers

1
votes

i want it to only display 1 blog post. how can i do that in the while loop? thanks

Do you understand that the while loop is specifically used to display multiple posts?

As another user points out, you can modify the query to only select one post. However, if you're working with the main query or another subquery that you cannot change, to display a single post, you don't need a while loop

query_posts('cat=1');
if (have_posts()) {
  the_post();
  the_title();
}
else {
  echo 'sorry no posts';
}

If you must keep the while loop for whatever reason, you can break after the first one is displayed

while (have_posts()) {
  the_post();
  the_title();
  break;
}

Last remark is about your use of if before while. It makes no sense

<?php if (have_posts()): while (have_posts()): the_post() ?>
  ...
<?php endwhile; endif; ?>

can be rewritten to

<?php while (have_posts()): the_post() ?>
  ...
<?php endwhile ?>
1
votes

Update the query_posts to use the posts_per_page parameter:

query_posts('cat=1&posts_per_page=1');

Which will only grab one post at a time.

https://developer.wordpress.org/reference/functions/query_posts/#more-information