0

I'm trying to create an image gallery which is comprised of all of the images attached to posts. The query below works well, but it ends up with all attached images rather than just the images actually used in the published post and post gallery. Unfortunately on some posts there are 20 attachments with only 10-15 of them being used within the actual post.

Is there a way to modify this query which will return only the images which have been used within the posts and post galleries?

// Get All Post IDs
$post_image_query = new WP_Query( 
    array( 
        'post_type' => 'post', 
        'posts_per_page' => -1,
        'fields' => 'ids'
    ) 
);

// Get All Attachments of Posts from $post_image_query 
$the_query = new WP_Query( 
    array(
        'post_type' => 'attachment',
        'post_status' => 'inherit',
        'post_parent__in' => $post_image_query->posts
    );
);
0

After doing a bit more research I was able to figure out a way to do this, though it seems like it probably isn't a great solution because it takes way way too long to run as it basically just loops through every post using get_post_gallery().

Perhaps there is a better way though - maybe someone else has thought about this before.

// Get All Post IDs
$post_image_query = new WP_Query( 
    array( 
        'post_type' => 'post', 
        'posts_per_page' => -1,
        'fields' => 'ids'
    ) 
);

$selected_posts = $post_image_query->posts;
$image_list_array = array();

// Loop through all posts and grab the image gallery
foreach($selected_posts as $post) {

    $post_gallery = get_post_gallery( $post, false );

    //retrieve individual ids from string
    $image_ids = explode(',', $post_gallery['ids']);

    //build the array
    foreach($image_ids as $image_id) {
        $image_list_array[] = $image_id;
    }
}

// Get All Attachments of Posts from $post_image_query 
$the_query = new WP_Query( 
    array(
        'post_type' => 'attachment',
        'post_status' => 'inherit',
        'orderby' => 'post_parent__in',
        'post_parent__in' => $image_list_array
    )
);
| improve this answer | |

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.