Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use JQuery.ajax to get the thumbnail attachment from each WordPress post?

I'm trying to get a JSON response showing thumbnail attachments for each WordPress post.

I tried using the JQuery json-api plugin, but it gives me all attachments. I just want the thumbnail.

For example, I would like to use JQuery.ajax to get the thumbnail attachment urls from each WordPress post in JSON format, like this:

[{image_1: "thumbnail_image_a.jpg",
image_2: "thumbnail_image_b.jpg",
image_3: "thumbnail_image_c.jpg",
... etc}]

Should I write my own plugin? Or add something to functions.php? Or what is the least complex way?

like image 515
edt Avatar asked Jul 26 '11 00:07

edt


1 Answers

I think you should take a look at https://solislab.com/blog/5-tips-for-using-ajax-in-wordpress/ ( old site is down : http://www.garyc40.com/2010/03/5-tips-for-using-ajax-in-wordpress/#admin-ajax ).

By adding a simple function with the right hooks in your functions.php you could end up with a nice way of getting exactly what you want.

Adapted from the url mentioned above:

add_action( 'wp_ajax_nopriv_myajax-submit', 'myajax_submit' );
add_action( 'wp_ajax_myajax-submit', 'myajax_submit' );

function myajax_submit() {
// get the submitted parameters
   $postID = $_POST['postID'];

   $response = get_thumbnail_images(); 
   $response = json_encode($response);

// response output
   header( "Content-Type: application/json" );
   echo $response;

// IMPORTANT: don't forget to "exit"
exit;
}

I call get_thumnail_images() where I might have a WP_Query or a SQL statement to get the information you need into an array.

Let's recap the wordpress part: 1) hooks

2) function that get's called based on the action parameter requested by the AjaxRequest (see url for full tutorial)

3) a logic function that will give us the thumbnails

4) the result is a json enconded array. You can do whatever you want with it on the front end.

like image 59
Vlad Nicula Avatar answered Oct 14 '22 15:10

Vlad Nicula