如何避免重复相同的meta_value?

时间:2012-06-22 作者:Bezbeli

我将“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值?

1 个回复
最合适的回答,由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>\';

结束

相关推荐

wp_nav_menu sort order?

嘿,伙计们,我正在尝试构建一个右对齐、包装功能良好的wp\\U nav\\U菜单供电菜单。有没有办法让它向后渲染,这样float:对;这样就行了,不会打乱秩序吗?我希望这样:<?php wp_nav_menu( array(\'sort_order\' => \'DESC\' )); ?> 谢谢!