Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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="post-permalink">Title</a></li>
            <li><a href="post-permalink">Title</a></li>
            <li><a href="post-permalink">Title</a></li>
            <li><a href="post-permalink">Title</a></li>
            <li><a href="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!

share|improve this question
    
You will need to call the loop and extract the information for each post e.g. the_title() etc. Also, first check if there is any result or not using have_posts() function –  booota Aug 21 '11 at 18:42
add comment

2 Answers

up vote 2 down vote accepted

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="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
    <?php
    }
    ?>
    </ul>
    <div><a href="#">View More</a></div>
    <?php
}
?>
</div>
share|improve this answer
1  
Thanks so much! This worked perfectly, however when I copied and pasted, it threw a php error, but was easily fixed when adding <?php to line 15 of your code block. Thanks again! –  Josh Allen Aug 22 '11 at 4:08
    
Whoops! Thanks for fixing that. That's what I get for not testing :) –  helenhousandi Aug 22 '11 at 15:10
add comment

You will need to use a foreach loop since you this query give an array of objects, inside this loop you can use the properties of these objects for show the data. By example you can use:

$object->post_title, $object->post_content, $object->url

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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