Find All Posts Containing Given Image In WordPress
Pass the id of the image to the function and it will return an array with the id’s of all the posts that use the given image.
/**
* Find all posts that uses the given image
*
* @param $image_id Integer ID of the image to work on
* @return Array An array of all the post ID's that use the image
* @credit https://wordpress.org/plugins/find-posts-using-attachment/
* @refer https://millionclues.com/wordpress-tips/find-posts-containing-given-attachment/
*/
function ablmc1327_get_posts_using_attachment ( $image_id ) {
$attachment_url = wp_get_attachment_url($image_id);
$search_content_query = new WP_Query( array(
's' => $attachment_url,
'post_type' => 'any',
'fields' => 'ids',
'no_found_rows' => true,
'posts_per_page' => -1,
));
return $search_content_query->posts;
}