0

I have a basic slider plugin that I am attemping to make more efficient. This plugin collects an array of attachment ID's from the user to represent each image of the slider.

With these attachment ID's, I then need the URL for a specific crop size on each one. I'm trying to figure out what the most efficient way to grab all of these is, in terms of querying the database.

Currently I'm doing something like this:

$attachments = array(1906,1905,1904); // attachment ID's from user

foreach( $attachments as $attachment_id ) {
    $image_url = wp_get_attachment_image_src($attachment_id, 'my_size');
    // $image_url[0] ...
}

However, am I correct in assuming that this means I'm querying the database each time I call wp_get_attachment_image_src()? Is there anyway to accomplish retrieving the URL's of each image with a single database query?

Can I do anything moving more in this direction?

$attachments = array(1906,1905,1904); // attachment ID's from user

$query = array('post_type' => 'attachment', 'post__in' => $attachments);
$posts = get_posts($query);

foreach( $posts as $post ){
    // Can I get the image URL of a specific crop size 
    // with out querying the DB again?

    // Possibly with $post->guid somehow?
}

Note: I understand the sort of insignificance of this basic example, in terms of the first way being "fine" but I'm trying to use this as more of a learning question in moving onto more complicated things. :)

0

I don't believe there is more efficient way. Your primary object should be keeping things simple while using WP's API which is exactly what you're already doing. It's true some scenarios could become pretty expensive and that is where you could take advantage of WP Object Cache or even Transients API. A good example of cache usage are the default widgets found in wp-includes/default-widgets.php

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.