0

I have searched Stack and the codex but can't find a simple solution for limiting the number of posts returned to one using the following:

<?php query_posts('cat=24'); ?> 
    <?php while (have_posts()) : the_post(); ?>
      <?php the_field('alert'); ?>
    <?php endwhile;?>

2 Answers 2

1
<?php query_posts('cat=24&posts_per_page=1'); ?>

But using query_posts is a very bad idea.

This is straigt from the Codex:

For general post queries, use WP_Query or get_posts.

It is strongly recommended that you use the pre_get_posts filter instead, and alter the main query by checking is_main_query.

0
0

Thanks to Dejo for the correct answer on this. I just wanted to post what this would look like using the get_posts approach he mentions above:

<?php               
$args = array( 'posts_per_page' => 1, 'offset'=> 0, 'category' => 24 );
$myposts = get_posts( $args );
foreach ( $myposts as $post ) : setup_postdata( $post ); ?>
<?php the_field('alert'); ?>
<?php endforeach; 
wp_reset_postdata();
?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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