tags:

views:

15

answers:

1

I've got a little sidebar that displaying in the code before the main page content. I wrote this (janky) function to pull in recent posts and comments. Works great, however, its screwing with all my pages and putting posts on all of them. How do I reset/rewind the query or make a new one so all my pages display the correct content?

<?php rewind_posts(); ?>and<?php wp_reset_query(); ?> arent doing the trick for me

Here is my query:

$comments = get_comments('number=10');
$posts    = get_posts('posts_per_page=10&category=6');


$most_recent = array();

foreach ($comments as $comment)
    $most_recent[strtotime($comment->comment_date_gmt)] = $comment;

foreach ($posts as $post)
    $most_recent[strtotime($post->post_date_gmt)] = $post;

unset($comments, $posts);

krsort($most_recent);

$most_recent = array_slice($most_recent, 0, 10);

foreach ($most_recent as $post_or_comment) {

    $is_post  =    isset($post_or_comment->post_date_gmt);
    $comment_id =   $post_or_comment->comment_ID;
  $post_id =    $post_or_comment->ID;  
 $comment_post_id =   $post_or_comment->comment_post_ID; 

 if ($is_post == 1) 

   { ?> <li><a href="<?php  echo get_permalink($post_id); ?>"><?php echo $post_or_comment->post_title; ?></a><span class="tag"><?php echo the_category($post_id); ?></span></li><?php } 

 else 
   { ?><li> <a href="<?php  echo get_permalink($comment_post_id); ?>"><?php echo get_the_title($comment_post_id); ?></a><span class="tag">Comment</span></li><?php }

    // output comments and posts
}

output comments and posts }

A: 

Try using $my_posts and $my_comments instead, just in case WP is using samely-named globals (though I don't think it is).

Also, in your foreach loop, you should only be casting variables when you know the object type, otherwise you're accessing non-existent properties;

foreach ($most_recent as $post_or_comment) {

    $is_post  =    isset($post_or_comment->post_date_gmt);
    if ($is_post) {
        $post_id =    $post_or_comment->ID;  
    } else {
        $comment_id =   $post_or_comment->comment_ID;
        $comment_post_id =   $post_or_comment->comment_post_ID; 
    }
}

rewind_posts() will have no effect here. Just call wp_reset_query() right after the foreach loop ends.

TheDeadMedic
That worked great. Thanks for your help, I didn't mean to say your code was janky, I meant it was the best way to do it in WP. I appreciate the help :)
Wes
Only kidding - 'tis janky, no doubt about it, but it could be far jankier ;)
TheDeadMedic