Wordpress get attachment of post doesn't work

孤者浪人 提交于 2019-12-31 04:57:46

问题


I'm trying to retrieve all the attachment of a specific post, but it doesn't work for the moment. Here is the code :

    $args = array(
        'post_type' => 'attachment',
        'posts_per_page' => -1,
        'post_parent' => $id
    );
    $attachments = get_posts($args);

Where Id is the id of my post. I've tried also with new WP_Query() but it didn't worked neither. Both ways return an empty result.

Does anyone have an idea what I'm doing wrong here ?

Thanks

EDIT

Ok, I think I know what's going wront. When using this arguments for the get_posts function, it will return the images uploaded through the "Add a media" button in the specific post.

So basically, let's say that on my first post, I've uploaded all the images I would need for all my future post. If I apply the request on the first post, I will retrieve all the images, even the one that I don't use in this post. If I apply this function to another post, because I didn't uploaded any file in this post, the function will retrieve an empty array.

Does anyone have an idea how I can retrieve all the images used in a specific post ? So not only uploaded, but really integrated into the post or added to a custom field ?

Thanks


回答1:


When using get_posts to fetch attachments, you need to set post_status to inherit. Also, check out the get_children function:

$args = array(
    'post_type' => 'attachment',
    'post_mime_type' => 'image',
    'numberposts' => -1,
    'post_status' => 'inherit',
    'post_parent' => $id
);
$attachments = get_children( $args );



回答2:


Case: using ACF, I created an repeater field 'resort_pics' for my gallery, which has 2 fields 'picture_title' as text and 'picture' as an picture type.

Then happily uploaded 100 photos, some of them were same for several posts so I only clicked those from uploaded gallery (I will use term of "referenced images" for those).

Problem : then one happy day I noticed all "referenced images" are missing in our api.

Cause : As noted at documentation comment from 'Uriahs Victor' (https://developer.wordpress.org/reference/functions/get_attached_media/)

Important to note that this function only returns the attachments that were first uploaded/added to the post. Uploading an image to Post A(ID 1) and then adding that image later to Post B(ID 2) would give an empty array if the following code was used:

$media = get_attached_media( 'image', 2 );
var_dump( $media );

Real cause : Real source of all this problem is The thing that information about "reference images" are not stored in 'wp_posts' table but are actually stored in 'wp_postmeta', so by just querying 'wp_posts' table or using get_attached_media() which only looks there also you will not get all attachements for post.

Solution : Lets take an example of post with ID - $postId which has defined repeater - 'resort_pics', field in repeater with image 'picture'. (created with ACF plugin)

First get all attachements for our post (resort) (including images/pdfs and so on) with classic way (can be also used 'get_attached_media'):

$images = $wpdb->get_results("select ID,guid from wp_posts where post_parent = " . $postId . " and `post_type`= 'attachment'");

where guid is 'url' to an attachement, lets index those in array where key will be post id of an attachement

$mapImages = [];
foreach ($images as $image) {
    $mapImages[$image->ID] = $image->guid;
}

Now we have all atachements but are missing all referenced images/files.

Lets continue by selecting all meta for our post (resort).

$metas = $wpdb->get_results("select meta_key,meta_value from wp_postmeta where post_id=" . $postId);

And index them by an meta key

$mapMetas = [];
foreach ($metas as $meta) {
    $mapMetas[$meta->meta_key] = $meta->meta_value;
}

Lets say our post ($postId) has an 9 entries in 'resort_pics' with an image uploaded to its 'picture' field, then $mapMetas['resort_pics'] will have an value of 8. Now the way how repeater fields keys are stored in $mapMetas array, is actually an :

'resort_pics_0_picture' -> itsPostId (5640 for example)
'resort_pics_1_picture' -> itsPostId (5641 for example)
'resort_pics_2_picture' -> itsPostId (5642 for example)
...
'resort_pics_8_picture' -> itsPostId (5648 for example)

Knowing this we can get simply all image urls for "resort_pics"

for ($i = 0; $i < $mapMetas['resort_pics']; $i++) {
    $picture = [];
    $picture['name'] = $mapMetas['resort_pics_' . $i . '_picture_title'];
    $picture['url'] = $mapImages[$mapMetas['resort_pics_' . $i . '_picture']];
    $pictures[] = $picture;
}

You may already get to this point, simply from $mapMetas get image ID and using it get an image url from $mapImages.

Lets say 'resort_pics_1_picture' is 'referenced' one (not directly uploaded image), we have its id '5641' but since its not connected to our $postID but to some other post id when it was actually uploaded. Its missing in our $mapImages array, so lets edit this code a bit.

for ($i = 0; $i < $mapMetas['resort_pics']; $i++) {
    $picture = [];
    $picture['name'] = $mapMetas['resort_pics_' . $i . '_picture_title'];
    $picture['url'] = getAttachmentOrItsReferenceUrl('resort_pics_' . $i . '_picture', $mapImages, $mapMetas);
    $pictures[] = $picture;
}

We have added an getAttachementOrItsReferenceUrl() method, which will simply first check if we already have this image (all uploaded to this post) and if not will fetch image data by its post id from 'wp_posts' table..

function getAttachmentOrItsReferenceUrl($code, $allAttachmentById, $allPostMetaByKey) {
    global $wpdb;
    $attachmentUrl = $allAttachmentById[$allPostMetaByKey[$code]];
    if($attachmentUrl === null && isset($allPostMetaByKey[$code]) && $allPostMetaByKey[$code] !== '') {
        $attachments = $wpdb->get_results("select ID,guid from wp_posts where ID = " . $allPostMetaByKey[$code]);
        foreach ($attachments as $image) {
            return $image->guid;
            break;
        }
    } else {
        return $attachmentUrl;
    }
    return "";
}

Finnal thoughts : If you know your fields structure you can build up its key pretty straightforward For an example 'rooms' repeater which has inside 'room_gallery' repeater which has inside 'image' image field.

'rooms_0_room_gallery_0_image'
--
$mapMetas['rooms'] - number of rooms
$mapMetas['rooms_' . $i . '_room_gallery'] - number of gallery images for room 
--
'rooms_' . $i . '_room_gallery_' . $j . '_image'

How heavy is it ? Not really, if you are like me, having only small amount of referenced images you wont even feel it. All we added to load is an one meta query for an post, if no images are referenced that's all, then for every referenced image there is one more query, but its query on ID should be fast. There is a lot of way how to make load less, for example not do query for every single missing image, but do single query at the end with 'where in (id1,id2..)' to have single query to get all, or after fetching new image data, store it in some global array by its id, and check this array before fetching image for next posts (so if one image is stored in 200 posts, and you are fetching all it would make only 1 query), you got the point I leave it just at the ideas since this is bloody long post even without that :)

Hope this will help anybody in future.



来源:https://stackoverflow.com/questions/16627394/wordpress-get-attachment-of-post-doesnt-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!