I'm trying to write an image gallery plugin with jQuery. I'm using jQuerys $.post AJAX method to send and receive info from the relevant post page. Basically I'll be looping through the attachments and adding a new image each time the next button is hit, until I've used all images (when I'll need to return something to stop the AJAX, not figured out how yet...).

I've read some very conflicting info on how to do this. I would very much like to know how I access WP data and functions from another PHP file. Any ideas? I'm threadbare, stressed and generally out of my mind with this one : )

  • Have you looked into ajax already? First try to set up your base, then add details about stuff that doesn't work, so we got something to solve.
    – kaiser
    Oct 1, 2012 at 16:57
  • Well, I've got it working with a normal php file, I pass a value, I get an image back. I know what my loop looks like, that's not the issue either. It's literally about connecting the two, as I just get errors when calling functions like have_posts()..
    – Dan
    Oct 1, 2012 at 17:15
  • That's not how AJAX in WP works. Please stick with the default way, or use one of the answers below.
    – kaiser
    Oct 1, 2012 at 18:01

2 Answers 2


As @MatthewBoynes already stated, making a $.post() request for every image might bring some overhead.

A maybe better solution would be to grab and cache them, then throw them into your js files using wp_localize_script().

$attachments = get_posts( array(
     'post_parent'    => get_the_ID()
    ,'post_type'      => 'attachment'
    ,'posts_per_page' => -1
    #,'exclude'        => get_post_thumbnail_ID() // only needed if we want to exclude the feat. image
) );

// Hook those to `wp_enqueue_scripts`
    ,array( 'jquery' )
    ,filemtime( get_template_directory().'/js/gallery.js' )
    ,json_encode( $attachments )

Then you can access the gallery_object from inside your ~/js/gallery.js file and move to the next image with an .on() click handler.

  • I know nothing about this kind of method, whats load time going to be like with this script? Do I use json_decode() to get the images for html output? I know nothing about json, sadly!
    – Dan
    Oct 1, 2012 at 18:28
  • Please read about ajax. The wp_localize_script() function allows to transfer PHP data as a javascript object. You then have access to this object in all your JS files. You'll see similar methods on different ajax questions. It doesn't matter if you're using AJAX or not - with the described method you're able to use the attachments in js.
    – kaiser
    Oct 1, 2012 at 18:38
  • Thanks Kaiser, I'll read up on the function. The two options I've been given look very different so I'll try and identify what's the simplest for this project as time is becoming a pressing issue.
    – Dan
    Oct 2, 2012 at 8:33
  • I've been doing some more work on this, would this script go in the template file? It looks like a functions.php thing to me..? The problem being several pages need this functionality so I can't have a function/loop per page as I don't know how many there will be...
    – Dan
    Oct 5, 2012 at 20:21
  • Simply build a small plugin for that. That way you're not forced to rebuild that functionality when changing theme.
    – kaiser
    Oct 6, 2012 at 15:58

Using ajax here would probably not be in your best interest (with one exception, see below). First, you'll be creating unnecessary calls to your server to query on each image. Second, the results won't be able to be cached, especially if you're making POST requests (which would not be the correct HTTP method/verb for this, as you aren't changing anything; in your example, you'd want to use GET requests [$.get() in jQuery ajax speak], but I digress). Third, it will be slow for the user.

Your best bet would be to loop through your posts in the initial page call and output the image URLs to a javascript array, or output your posts array as JSON. You could also loop through and output <img> tags, but then images would load upfront and not on request (whether or not that's a good thing depends on the site and the images). I'd go with the first option, and here's how I'd get it started:

<script type="text/javascript">
var my_images = [
# Here is where you'll loop through your attachments

The only exception to this is if you had lots of images, e.g. >100 per page. In that case, you'll have to find the right balance and do ajax calls for batches of images, combining what you're asking with what I suggested above.

Good luck!


On second thought, what I'd do is output a list of links to the images, with the titles as the link text, then use JS to read it out, setup the slideshow, and dynamically load the images (the link tag's href) on-demand. This is really no different from the JS array, except the data is stored in HTML. Because it's in HTML, it carries some distinct advantages: browsers with JS disabled will still be able to access the photos, you'll have captions for the images, search engines spiders which don't process JS will still index the images, and your hopefully-keyword-rich image titles will also be read by the spiders. Here's how you'd set this up, pulled in part from the codex:

    <?php if ( have_posts() ) : while ( have_posts() ) : the_post();
    $attachments = get_posts( array(
        'post_type' => 'attachment',
        'numberposts' => -1,
        'post_status' => null,
        'post_parent' => $post->ID
    ) );
    if ( $attachments ) foreach ( $attachments as $attachment ) : ?>
    <li><a href="<?php echo wp_get_attachment_url( $attachment->ID ); ?>"><?php echo apply_filters( 'the_title', $attachment->post_title ); ?></a></li>
    <?php endforeach; ?>
  • Hi Matthew, thanks for writing. It's going to be about 30 images per page, but they will be larger file sizes as the plugin is designed to fill most of the browser window. It's all responsive so the height of the images is set depending on what the user is viewing on. It's simply too much to load in one go...what do you think would work best?
    – Dan
    Oct 1, 2012 at 17:57
  • If you go the javascript route (either sources in an array as my code sample setup, or outputting a JSON object), the images won't load until your javascript calls them. Therefore, you're only making one page load, but you're still getting an ajax-like effect where images aren't loaded unless needed. That's definitely the route I'd go! Oct 1, 2012 at 18:11
  • I just had a better idea which I'll append to my answer. Oct 1, 2012 at 18:16
  • This sounds like a great option for me, as this project demands good SEO. I don't know how to get JS to "read out" the images as you say, I'm assuming I'll have a trigger (click) which will ask JS to fetch the next image. Is this a pre-made function or something? Also, once it's loaded will my jQuery still be able to set the dimensions with css() and re-calculate the new width of the overall amount of images? My slider is dependent on the jQuery knowing a lot of image dimensions...
    – Dan
    Oct 2, 2012 at 8:32
  • At this point, we're escaping WordPress land. There are scores of docs on jQuery that will help you make this happen. And if you can't figure it out, you could hire someone on Craigslist to plow through this on the cheap. Best of luck! Oct 2, 2012 at 12:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.