0

I need to display only the last 3 posts but i get 10 posts (Reading Settings).

Any idea ?

<?php
$args = array( 'post_type' => 'post', 'posts_per_page' => 3);
$wp_query = new WP_Query($args);
while ( have_posts() ) : the_post(); ?>

            <h4>
                <a href="<?php the_permalink() ?>"><?php the_title(); ?></a>
            </h4>
            <?php the_excerpt(__('(more…)')); ?>

<?php endwhile; ?>
<?php wp_reset_postdata(); ?>

1 Answer 1

3

In your loop, you must refer to $wp_query instance:

<?php
$args = array( 'post_type' => 'post', 'posts_per_page' => 3);
$wp_query = new WP_Query($args);
if ( $wp_query->have_posts() ) {
    while ( $wp_query->have_posts() ) : $wp_query->the_post(); ?>
        <h4><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h4>
        <?php the_excerpt();
    endwhile;
} else {
    echo 'No posts';
}
wp_reset_postdata();
?>

Also, the_excerpt() function takes one optional parameter, which is either Post ID or $post object. To control 'more' link, you use 'excerpt_more' filter.

2
  • That doesn't change anything. It keep showing 10 posts. Commented May 12, 2017 at 7:59
  • I've tested it. it works. Give me more info. Where did you use it? Did you get any errors. Check error_logs if any. Commented May 12, 2017 at 15:09

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.