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 use the following code to extract the attached images from a post with 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);

The problem is that the above code return all the attached files. Is there a way to remove from the results the featured image ? I don't mind if I will do it through the $args query, by some if statement or by filtering the $attachments array.

Kind regards Merianos Nikos

share|improve this question

3 Answers 3

up vote 3 down vote accepted

Simply add an exclude argument and use the get_post_thumbnail_id() function.

$args = array(
    'post_type'      => 'attachment',
    'post_parent'    => $product_id,
    'post_mime_type' => 'image',
    'orderby'        => 'menu_order',
    'order'          => 'ASC',
    'numberposts'    => -1,
    'exclude'        => get_post_thumbnail_id($product_id)
);
$attachments = get_posts($args);
share|improve this answer
    
+1 for exclude... –  Joshua Abenazer Aug 22 '12 at 10:07

Yes,

basicaly what you want is this

<?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
    }
share|improve this answer

Try this after your above code.

foreach( $attachments as $key => $attachment ) {
    if ( $attachment->ID == get_post_thumbnail_id( $product_id ) ) {
        unset ( $attachments[$key] );
        break;
    }
}

Now $attachments would contain all the attachments of $product_id except the featured image.

share|improve this answer

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.