I’m working on a WP_Query()
, where I’m trying to fetch all the images using 'post_type' => attachment
and 'post_parent_in' => array( 1688 )
(I want to pass some more post_ids) along with other parameters. With these I can fetch all the attachments, but the featured image.
I attached two different images into a post to check the thing. Then I sneaked into the WordPress database, and in ‘posts
‘ table, I found the two images are there as 'post_type' => 'attachment'
, and 'post_mime_type' => 'image/jpeg'
.
But…
in ‘post_parent
‘ one image is attached with the post with the post id (1688), but the other is showing Zero (0). I found that, only the images, those are inserted into a post are getting post_parent
, but the featured image.
And the same attachment is in postmeta
table:
So, currently I’m unable to get all the attachment that are attached to some posts.
And, I wonder, HOW THE FEATURED IMAGES ARE ATTACHED WITH THE POSTS?
You can upload images in 2 places:
Media page (
uploads.php
) or from Add Media button in a post/page edit page.When you upload images from the post edit screen,
'post_parent'
for all images uploaded is set to current post.When you upload images from the Media page,
'post_parent'
is set to0
.When an image you have uploaded on media page is first inserted in the content of a post, or is included in a gallery inside the post, the
'post_parent'
field is changed to the current post, just like it was uploaded using Add Media button of post edit screen.As you noticed this does not happen for featured images, when an image uploaded on media page is used as featured image for a post, its
post_parent
stay unchanged.Only thing that change is that a meta field
'_thumbnail_id'
is created for the post and its value is setted to the id of attachement post.So if your post id is
10
,get_post_meta(10, '_thumbnail_id', true);
will return the ID of the post thumbnail.Note that an image with
post_parent
setted to a post id does not mean that it’s inserted in the content of the post, it can be uploaded using the post Add Media button, but never inserted in the post content.Also the countrary is true, an image inserted in the content of a post can have a
post_parent
setted to another post id.