我将“publication\\u year”作为一些图像/附件的meta\\u键。我想列出html表中的所有meta\\u值,但我不想重复相同的publication\\u year值,我的代码是:
<?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>\';
有了它,我得到了:
2002 imageDesc1
2003 imageDesc2
2003 imageDesc3
2003 imageDesc4
2004 imageDesc5
但我想要这个:
2002 imageDesc1
2003 imageDesc2
imageDesc3
imageDesc4
2004 imageDesc5
因此,如果有具有相同出版年份的附件,我希望它们分组,而不是重复,如何避免重复相同的meta\\u值?
最合适的回答,由SO网友:Andy Adams 整理而成
一种方法是跟踪您已经打印的年份。使用您的代码:
<?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>\';