Nice one Fab1en,
Your solution was much more elegant than mine!
Here is his git: https://github.com/wp-plugins/find-posts-using-attachment
I had created a initial function to make an array of ALL galleries from all posts on plugin load, than checked the array once each attachment ID was run.
Main function, thought it might be lower overhead instead of running the database call every time.
// Get all posts with galleries and thier IDs
public $post_gallery_urls=array();
function get_all_galleries_from_posts() {
$the_gallery_images = array();
$post_galleries_query = new WP_Query( array(
's' => '[gallery',
'post_type' => 'any',
'fields' => 'ids',
'no_found_rows' => true,
'posts_per_page' => -1,
) );
$theposts = $post_galleries_query->posts;
foreach($theposts as $post_gallery_id){
$galleries = get_post_gallery($post_gallery_id,false);
$this->post_gallery_urls[] = array('post_id'=>$post_gallery_id,'images'=>explode(',',$galleries['ids']) );
};
}
Checking if in array
//Custom code to check for images in galleries
$used_in_gallery = array();
if ( wp_attachment_is_image( $attachment_id ) ) {
foreach ($this->post_gallery_urls as $galleries ) {
if(in_array( $attachment_id , $galleries['images'] )){
$used_in_gallery[] = $galleries['post_id'];
}
}
}
Than later on and updated the output to show “In Gallery” text.