How to use jQuery.ajax to get an attachment in every WordPress post?

I am trying to get a JSON response showing attachments for each WordPress post.

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

For example, I would like to use jQuery.ajax to get the attachment URLs for each WordPress post in JSON format, for example:

[{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 difficult way?

+6
source share
2 answers

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

By adding a simple function with the right hooks to functions.php , you can get a great way to get exactly what you want.

Adapted to the above address:

 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 can have WP_Query or an SQL statement to get the necessary information in an array.

Let's list the wordpress part: 1) hooks

2) that are called based on the action parameter requested by AjaxRequest (see url for the full tutorial)

3) a logical function that will give us thumbnails

4) the result is an array associated with json. You can do whatever you want with it on the front side.

+7
source

You will need to use $ .ajax to load the page through its URL, then you will have to sort the markup to find each message and get a thumbnail from it. I do not know the markup for the wordpress site, so I can not help you.

It might 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 } } }); 
0
source

Source: https://habr.com/ru/post/893538/


All Articles