get( 'show_thumbnails', true ) : true; } /** * @param int[] $post_ids * @return array post ID → thumbnail URL ('' when none / disabled) */ public static function urls( array $post_ids ): array { $ids = array_values( array_unique( array_filter( array_map( 'intval', $post_ids ) ) ) ); $out = array_fill_keys( $ids, '' ); if ( ! $ids || ! self::enabled() ) return $out; update_meta_cache( 'post', $ids ); $att = []; foreach ( $ids as $id ) { $a = (int) get_post_meta( $id, '_thumbnail_id', true ); if ( $a ) $att[ $id ] = $a; } if ( ! $att ) return $out; if ( function_exists( '_prime_post_caches' ) ) _prime_post_caches( array_values( $att ), false, true ); foreach ( $att as $id => $a ) { $url = wp_get_attachment_image_url( $a, 'thumbnail' ); $out[ $id ] = $url ? (string) $url : ''; } return $out; } /** One URL (for single-post responses). */ public static function url( int $post_id ): string { return self::urls( [ $post_id ] )[ $post_id ] ?? ''; } /** * Add a thumbnail field to each row of a list, reading the post ID from $id_key. * Works for arrays of arrays and arrays of objects. */ public static function add( array $rows, string $id_key = 'id', string $field = 'thumb' ): array { $ids = []; foreach ( $rows as $r ) $ids[] = (int) ( is_array( $r ) ? ( $r[ $id_key ] ?? 0 ) : ( $r->$id_key ?? 0 ) ); $urls = self::urls( $ids ); foreach ( $rows as $k => $r ) { $id = (int) ( is_array( $r ) ? ( $r[ $id_key ] ?? 0 ) : ( $r->$id_key ?? 0 ) ); if ( is_array( $r ) ) $rows[ $k ][ $field ] = $urls[ $id ] ?? ''; else $rows[ $k ]->$field = $urls[ $id ] ?? ''; } return $rows; } }