putting a loop in your sidebar

The simplest way to put a loop in your sidebar is with Justin Tadlock’s sweet plugin Query Posts. This lets you use the query_posts function, with all of its options, in a widget.

However sometimes you might need a loop that does something unusual. I had a client who has a category of posts with natural history photos from near his home. He wanted an image to pop up, randomly selected, from the category. This can be done with Query Posts.

However, he didn’t want the image to link to the post—he wanted it to link to the category page. That’s why I wrote out a loop with php and put it in the functions.php file:

<?php function keyshots_widget() {
    $custom_query = new WP_Query('cat=15&posts_per_page=1');
    while($custom_query->have_posts()) : $custom_query->the_post();
    $category_link = get_category_link('15'); ?>
    <a href="<?php echo esc_url( $category_link ); ?>"> <?php
        if ( function_exists( 'get_the_image' ) ) { 
        get_the_image(array( 'link_to_post' => false, 'size' => 'sidebar' ));
        } ?></a>
        <p><a href="<?php echo esc_url( $category_link ); ?>"><?php the_title(); ?></a></p>
    <?php endwhile;
    $output = ob_get_contents();
    return $output;
    wp_reset_postdata(); // reset the query
add_shortcode("keyshots-widget", "keyshots_widget");

Note that the loop is wrapped in a function, and there is a shortcode that runs the function. You still need to set up your theme to run shortcodes in widgets (this is something I add to nearly every WP theme I make). You do it with this line in functions.php: add_filter('widget_text', 'do_shortcode');

Also, see the ‘output buffer’ in the loop above. You need that, or the post will display in the wrong spot.

It uses Get The Image, which is another of Tadlock’s plugins, to, well, get the image.

Leave a Reply