Forum Moderators: coopster

Message Too Old, No Replies

Stop duplicate output from within a Loop?

WordPress related too - if that helps.

         

doodlebee

7:47 pm on Jul 30, 2009 (gmt 0)

10+ Year Member



Okay - I need to somehow check if something's already been output in a loop, and not repeat it. (I'm using WordPress for this...but I think this is a PHP issue, not a WordPress one)

Basically, I want a list of authors to appear on the current page you're on - but ONLY the authors that are on the page. I have this working right now - just perfectly. It's doing *almost* exactly what I want:

if(have_posts()) : while(have_posts()) : the_post();
$author = get_the_author();
echo $author . '<br />';
endwhile; endif;

However, if there's two posts written by "Lionel", then "Lionel " is listed twice. So say the page has 6 posts, all written by 1) admin, 2) Lionel, 3) Jean, 4) Lionel, 5) Lionel and 6) admin. The above code outputs:

admin
Lionel
Jean
Lionel
Lionel
admin

What I *want* it to output is:

admin
Lionel
Jean

I can't quite figure out how to flag $author so that it only appears one single time, and no more than that.

Anyone got a tip for me on that one? XD

doodlebee

7:53 pm on Jul 30, 2009 (gmt 0)

10+ Year Member



well, I got it partly figured already:


function list_page_authors() {
$name = '';
if(have_posts()) : while(have_posts()) : the_post();
$author = get_the_author();
if($author != $name) {
$name = $author;
$count = 1;
}
if($count == '1') {
get_my_image('avatar');
echo $name . '<br />';
}
$count++;
endwhile; endif;
}

However, now it outputs:

admin
Lionel
Jean
admin

anyone know what that last "admin" is in there?

doodlebee

9:10 pm on Jul 30, 2009 (gmt 0)

10+ Year Member



Got it. Hopefully this helps someone else in the future :)


function list_page_authors() {
global $post, $root, $path;

$output = array();
if(have_posts()) : while(have_posts()): the_post();
$id = get_the_author_meta('ID');
$id_arr[] = $id;
endwhile; endif;

$clean = array_unique($id_arr);
foreach($clean as $id) {
$first = get_the_author_meta('first_name', $id);
$last = get_the_author_meta('last_name', $id);
$name = $first . ' ' . $last;
$img = '/wp-content/gravatars/' . $first . '_' . $last . '.jpg';

if(file_exists($root . $img)) {
$myimg = '<img class="avatar" src="' . $path . $img . '" alt="' . $name . '" />';
} else {
$myimg = get_avatar( $post );
}

echo $myimg;
echo $name . '<br />';
}
}