Detect featured image among the attached images

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

3 Answers
3

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);

Leave a Comment