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 have "publication_year" as meta_key for some images/attachments. I want to list all meta_values inside html table, but I don't want same publication_year value to repeat, my code is:

<?php $args = array( 'post_type' => 'attachment',
                     'post_mime_type' => 'image',
                     'numberposts' => -1,
                     'orderby' => 'menu_order',
                     'order' => ASC
                     );
$attachments = get_posts( $args );
echo '<table id="bibliography">';
if ($attachments) {
foreach ( $attachments as $post ) {
    setup_postdata($post);
    echo '<tr><td>';
    if ( get_post_meta( $post->ID, '_publication_year', true )) {
         echo get_post_meta( $post->ID, '_publication_year', true );
        };
    echo '</td><td>';
    echo '<a href="';
    the_permalink();
    echo '">';
    echo get_the_excerpt();
    echo '</a></td></tr>';
    }
}
echo '</table>';

and with it I get this:

2002 imageDesc1
2003 imageDesc2
2003 imageDesc3
2003 imageDesc4
2004 imageDesc5

but I want this:

2002 imageDesc1
2003 imageDesc2
     imageDesc3
     imageDesc4
2004 imageDesc5

So if there are attachments with same publication years, I want them to group and not repeat How can I avoid duplicating same meta_value?

share|improve this question
add comment

1 Answer 1

up vote 3 down vote accepted

One way would be to keep track of which years you've already printed. Using your code:

<?php
    $args = array(
        'post_type' => 'attachment',
        'post_mime_type' => 'image',
        'numberposts' => -1,
        'orderby' => 'menu_order',
        'order' => ASC
    );

    $attachments = get_posts( $args );

    echo '<table id="bibliography">';

if ( $attachments ) {
            $already_printed_years = array();
    foreach ( $attachments as $post ) {
            setup_postdata( $post );
            echo '<tr><td>';
            $year = get_post_meta( $post->ID, '_publication_year', true );
    if ( get_post_meta( $post->ID, '_publication_year', true ) && ! in_array( $year, $already_printed_years ) ) {
            echo get_post_meta( $post->ID, '_publication_year', true );
            $already_printed_years[] = $year;
            }
            echo '</td><td>';
            echo '<a href="' . get_permalink( $post->ID ) . '">';
            echo get_the_excerpt();
            echo '</a></td></tr>';
    }
}
           echo '</table>';
share|improve this answer
    
It works!!! thank you very much :-) –  Bezbeli Jun 22 '12 at 23:37
add comment

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.