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.

Read More

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?

Related posts

Leave a Reply

2 comments

  1. 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.

  2. You would have to use $.ajax to download the page via it’s URL argument, then you would have to sort through the markup to find each post and get the thumbnail from it. I don’t know the markup for a wordpress site, so I can’t help you there.

    It may work something like this:

     $.ajax('url.php',{
            dataType: 'html',
            success: function(data){
                $.find('wordpress_comment_element').each(function(){
                    var thumb=$(this).children('img').attr('src');
                    //add thumb to JSON object
                }
            }
        });