在附加图像中检测特征图像

时间:2012-08-22 作者:KodeFor.Me

我使用以下代码从ID为的帖子中提取附加图像:

$args            =   array(
    \'post_type\'      => \'attachment\',
    \'post_parent\'    => $product_id,
    \'post_mime_type\' => \'image\',
    \'orderby\'        => \'menu_order\',
    \'order\'          => \'ASC\',
    \'numberposts\'    => -1
);

$attachments     =   get_posts($args);
问题是上面的代码返回了所有附加文件。有没有办法从结果中删除特色图像?我不介意通过$args查询、一些if语句或过滤$attachments数组来完成。

善良的regardsMerianos Nikos

3 个回复
最合适的回答,由SO网友:Brian Fegter 整理而成

只需添加post__not_in 参数并使用get_post_thumbnail_id() 作用

$args = array(
    \'post_type\'      => \'attachment\',
    \'post_parent\'    => $product_id,
    \'post_mime_type\' => \'image\',
    \'orderby\'        => \'menu_order\',
    \'order\'          => \'ASC\',
    \'numberposts\'    => -1,
    \'post__not_in\'   => array(get_post_thumbnail_id($product_id))
);
$attachments = get_posts($args);

SO网友:Joshua Abenazer

请在上面的代码之后尝试此操作。

foreach( $attachments as $key => $attachment ) {
    if ( $attachment->ID == get_post_thumbnail_id( $product_id ) ) {
        unset ( $attachments[$key] );
        break;
    }
}
现在$attachments 将包含的所有附件$product_id 除了特色图片。

SO网友:woony

基本上你想要的是这个

<?php  
//get post thumbnail url  
$post_thumbnail_id = get_post_thumbnail_id();  
$post_thumbnail_url = wp_get_attachment_url($post_thumbnail_id);  
//get your attachments. <- your query
//now loop your attachments <- foreach or something

 if($attachment->ID != $post_thumbnail_id)
    {
//if the attachment id is the same as your post_thumbnail_id it means you are looking at your feature image
    }

结束