Is there a function to check whether an attachment ID (=get_post_thumbnail_id(..)) is associated with more than one post?

With "associated" I mean that a posts's meta value for the meta_key _thumbnail_id equals the attachment ID.

I know that get_post_meta() returns an empty array if it does not find anything, but I would have to somehow loop over all posts.


you can use following way

$attachment_id = 5; //put here you attachment id
$sql = "SELECT count(DISTINCT pm.post_id) FROM $wpdb->postmeta pm JOIN $wpdb->posts p ON (p.ID = pm.post_id) WHERE pm.meta_key = '_thumbnail_id' AND pm.meta_value = '$attachment_id' AND p.post_type = 'post' AND p.post_status = 'publish'";
$count = $wpdb->get_var($sql);
| 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.