0

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?

1 Answer 1

3

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>';
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.