The correct way to call posts with ajax

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 : )

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`
wp_register_script( 
     'gallery'
    ,get_template_directory_uri().'/js/gallery.js'
    ,array( 'jquery' )
    ,filemtime( get_template_directory().'/js/gallery.js' )
    ,true
);
wp_localize_script(
     'gallery'
    ,'gallery_object'
    ,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.

Leave a Comment