1

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

4

Simply add an post__not_in 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,
    'post__not_in'   => array(get_post_thumbnail_id($product_id))
);
$attachments = get_posts($args);
1

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
    }
1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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