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'm trying to make a simple widget that displays a list of posts, and is followed by some metadata from each post.

Here is my code: $eventdate contains the metadata i need to retrieve.

query_posts('');

if (have_posts()) : 
    echo "<ul>";
    while (have_posts()) : the_post(); 
        $eventdate = get_post_meta($post->ID, 'event-date', true);
        echo "<li>".get_the_title()." - ".$eventdate."</li>";
    endwhile;
    echo "</ul>";
endif; 
wp_reset_query();

I read an old post on the wordpress support forums about custom loops like this, and I'm fairly certain that I'm not calling the $post_id properly, because if I manually insert a post_id it calls the correct data.. but either way I'm unsure where to go from here. Any help would be appreciated.

share|improve this question
2  
Could you post this as an answer, and then accept it as correct (you'll have to wait 24 hours). It takes it off the unanswered pile, and makes it easier for people to identify the solution. Thanks. –  Stephen Harris Mar 5 '12 at 13:25
    
I will, just waiting for the time to pass –  Northernlights Mar 5 '12 at 15:17
    
You can post the answer immediately :D –  Stephen Harris Mar 5 '12 at 15:23
    
If you're in the loop, it's a better practice to use get_the_ID() rather than declare global and use $post->ID –  Tom Mar 5 '12 at 15:33

2 Answers 2

up vote 0 down vote accepted

query_posts() is for main query, it would be more wise to use get_posts() function to get you events.

// Modify get_posts args for your needs
$events = get_posts( array ( 'post_type' => 'events' ) );

if ( $events ) {
    echo '<ul>';

    foreach ( $events as $event ) {
        $event_date = get_post_meta( $event->ID, 'event-date', true );

        echo '<li>' . get_the_title( $event->ID ) . ' - ' . $event_date . '</li>';
    }

    echo '</ul>';
}
share|improve this answer
    
Thanks.. using this now instead –  Northernlights Mar 6 '12 at 9:03
    
You're welcome. –  Mamaduka Mar 6 '12 at 9:16

Debugged and realised that $post in $post->ID needed to be declared a global variable. Sorted.

share|improve this answer
    
Why is get_the_ID() better @Tom ? –  Northernlights Mar 6 '12 at 6:53
    
Was it a nested loop? –  Kaaviar Mar 6 '12 at 8:47
    
only as nested as above code shows –  Northernlights Mar 6 '12 at 9:03
    
@Northernlights get_the_ID does the same thing, calls global $post and returns $post->ID –  Mamaduka Mar 6 '12 at 9:19

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.