0

I'm using a theme which has its own homepage which is created using the theme options (i.e. so can't add content under Pages) so I'm trying to add the latest posts on the page, I have copied the code from the blog themed page which is working great but its displaying all of the posts and I only wanted to display a pre-defined amount, probably 3 but I want to test it out.

I'm assuming the function I've attached below is retrieving every post I've made but I don't know much about PHP so I don't know how to only retrieve x amount of posts.

<?php if ( have_posts() ) : $count = 0; ?>
<?php while ( have_posts() ) : the_post(); $count++; global $post; ?>
1

The code you posted does not query for any content at all. To do that, use the WP_Query object. Please do not use query_posts, especially for secondary Loops. From the Codex:

// The Query
$the_query = new WP_Query( $args );

// The Loop
while ( $the_query->have_posts() ) :
    $the_query->the_post();
    echo '<li>' . get_the_title() . '</li>';
endwhile;

All you need to do is provide $args. In your case array('posts_per_page'=>3)

$args = array('posts_per_page' => 3); // or however many you want

// The Query
$the_query = new WP_Query( $args );

// The Loop
while ( $the_query->have_posts() ) :
    $the_query->the_post();
    echo '<li>' . get_the_title() . '</li>';
endwhile;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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