Created
April 29, 2022 06:20
-
-
Save avenirer/e93e6be67085922182280f44b2ac574e to your computer and use it in GitHub Desktop.
Get featured images for multiple posts at one time (in one query)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Get attachment image src for multiple posts at one time | |
* | |
* @param array $post_ids - The post IDs you want the featured image retrieved | |
* @param string $thumbnail_size - The thumbnail size name | |
* @return array - An array with the urls for the image srcs if they exist | |
*/ | |
function avenirer_get_attachment_image_src($post_ids = array(), $thumbnail_size = 'full') { | |
if(sizeof($post_ids) == 0) { | |
return []; | |
} | |
$post_ids_str = '(' . implode(',', $post_ids) .')'; | |
global $wpdb; | |
$qstr = 'SELECT post_id, meta_key, meta_value FROM wp_postmeta WHERE post_id IN (SELECT meta_value FROM wp_postmeta WHERE post_id IN ' . $post_ids_str . ' AND meta_key = "_thumbnail_id") AND meta_key = "_wp_attachment_metadata"'; | |
$results = $wpdb->get_results( $qstr, ARRAY_N ); | |
$attachments = []; | |
if($results) { | |
$upload_dir = wp_upload_dir(); | |
foreach($results as $featured) { | |
$metadata = unserialize($featured[2]); | |
if(array_key_exists($thumbnail_size, $metadata['sizes'])) { | |
$attachments[$featured[0]] = $upload_dir['baseurl'] . '/' . $metadata['sizes'][$thumbnail_size]['file']; | |
} | |
else { | |
$attachments[$featured[0]] = $upload_dir['baseurl'] . '/' . $metadata['file']; | |
} | |
} | |
} | |
return $attachments; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment