Grab 5 latest posts from custom post type ‘announcements’

I have a custom post type announcements which obviously holds posts with weekly announcements.

In my theme’s header, I want to create a box which has the following semantics:

<div id="header-announcements">
    <h3>Announcements</h3>
        <ul>
            <li><a href="https://wordpress.stackexchange.com/questions/26482/post-permalink">Title</a></li>
            <li><a href="https://wordpress.stackexchange.com/questions/26482/post-permalink">Title</a></li>
            <li><a href="https://wordpress.stackexchange.com/questions/26482/post-permalink">Title</a></li>
            <li><a href="https://wordpress.stackexchange.com/questions/26482/post-permalink">Title</a></li>
            <li><a href="https://wordpress.stackexchange.com/questions/26482/post-permalink">Title</a></li>
        </ul>
    <div><a href="#">View More</a></div>
</div>

I know I want to use wp_query() and I’ve found that I should do something similar to

ann-query = wp_query('post_type=announcements&posts_per_page=5');

I know I need to do a foreach, but I haven’t dived deep enough into wordpress to know what to do after the query.

Any help?

Thanks!

2 Answers
2

The following should work, but isn’t tested:

<div id="header-announcements">
<h3>Announcements</h3>
<?php
$queryObject = new WP_Query( 'post_type=announcements&posts_per_page=5' );
// The Loop!
if ($queryObject->have_posts()) {
    ?>
    <ul>
    <?php
    while ($queryObject->have_posts()) {
        $queryObject->the_post();
        ?>

        <li><a href="https://wordpress.stackexchange.com/questions/26482/<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
    <?php
    }
    ?>
    </ul>
    <div><a href="#">View More</a></div>
    <?php
}
?>
</div>

Leave a Comment