Load image src through Ajax by ID?

admin2025-06-02  3

I've been trying to optimize a site and on a warpath at decreasing db queries. One thing I am noticing that's very expensive is wp_get_attachment_image_src. On an overview page listing the entire contents of a section, my pages have an image id set in a custom field. If on that page I call wp_get_attachment_image_src it requires an additional DB query for each one.

Brainstorming the idea of just outputing the ID in HTML, render the page, and have JavaScript do an Ajax request to the server to do this additional query and get the src.

How would this be accomplished?

I've been trying to optimize a site and on a warpath at decreasing db queries. One thing I am noticing that's very expensive is wp_get_attachment_image_src. On an overview page listing the entire contents of a section, my pages have an image id set in a custom field. If on that page I call wp_get_attachment_image_src it requires an additional DB query for each one.

Brainstorming the idea of just outputing the ID in HTML, render the page, and have JavaScript do an Ajax request to the server to do this additional query and get the src.

How would this be accomplished?

Share Improve this question asked Oct 20, 2016 at 19:44 Louis WLouis W 4741 gold badge6 silver badges18 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

You would be better off preloading all the images for the current page ahead of actually outputting them. Then you reduce the queries from n*2 (there are actually two database queries per get image call, one from the wp_posts table, the other from wp_postmeta) down to just two.

$images = [];
foreach ( $pages as $page )
    $images[] = ( int ) get_post_meta( $page->ID, 'image_field', true );

if ( $images = array_filter( $images ) ) {
    new WP_Query([
        'post__in'       => $images,
        'posts_per_page' => -1,
        'no_found_rows'  => true,
        'post_status'    => [ 'publish', 'inherit' ],
        'post_type'      => 'attachment',
    ]);
}

This is just for demonstrative purposes, but the idea is you build an array of just image ID's, then use a query to pull them all into memory at once. Subsequent image function calls for said IDs will hit the cache rather than the database.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1748872276a314421.html

最新回复(0)