WordPress Loop in a Widget
When I was writing a WordPress widget plugin to display information from a sub set of my posts (that’s it on the side, with the paper toys…) I noticed that the WordPress Loop doesn’t quite behave itself when widgetized in the 2.8+ style.
When using the following code, inside a widget, to return posts from a custom query, you’ll find that the post title and perma-link are returned, but the post ID is not.
1 2 3 4 5 | <?php $loop = new WP_Query($query); while ( $loop->have_posts() ) : $loop->the_post(); ?> <a href="<?php the_permalink() ?>"> <?php echo $post->ID.' : @; the_title(); ?></a> <?php endwhile; ?> |
Adding a global call to the $post variable at the top of the loop fixes this issue.
1 2 3 4 5 6 | <?php $loop = new WP_Query($query); while ( $loop->have_posts() ) : $loop->the_post(); global $post;?> <a href="<?php the_permalink() ?>"> <?php echo $post->ID.' : @; the_title(); ?></a> <?php endwhile; ?> |