1

I am looking to display x (undecided) number of recent posts (no more than 10) on my home page. For each post, I would like to display the title and a snippet of the content. I can whip up a SQL query myself to get this but I was wondering what the WordPress function is to get this. The closest I have gotten is <?php wp_get_archives('type=postbypost&limit=10&format=html'); ?>. I would also like to custom format the HTML. An example of the output I would like looks like this

<div id="posts">
    <section class="post">
        <h2><a href="[post uri]">[post title]</a></h2>
        <p>[post snippet]</p>
    </section>
    <section class="post">
        <h2><a href="[post uri]">[post title]</a></h2>
        <p>[post snippet]</p>
    </section>
</div>
5
<div id="posts">

<?php

    // define query arguments
    $args = array(
        'posts_per_page' => 8, // your 'x' goes here
        'nopaging' = true
        // possibly more arguments here
    );

    // set up new query
    $tyler_query = new WP_Query( $args );

    // loop through found posts
    while ( $tyler_query->have_posts() ) : $tyler_query->the_post();
        echo '<section class="post">'.
             '<h2><a href="'.
             get_permalink().
             '">'.
             get_the_title().
             '</a></h2><p>'.
             get_the_excerpt().
             '</p></section>';
    endwhile;

    // reset post data
    wp_reset_postdata();

?>

</div>

By default an excerpt is 55 words long. For a custom excerpt length drop the following in your theme's functions.php:

function tyler_excerpt_length( $length ) {
    return 70; // change number of words to your liking
}
add_filter( 'excerpt_length', 'tyler_excerpt_length' );

If your not satisfied with the default "Continue reading" link at the end of the excerpt, drop this into functions.php:

function tyler_excerpt_more( $more ) {
    return 'Read the whole post &gt;&gt;'; // again, change to your liking
}
add_filter( 'excerpt_more', 'tyler_excerpt_more' );

If, since you have the post link in the title, you want the excerpt's "more" link not to display, have the above function return an empty string, i.e. return '';.

Further reading:

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.