0

I'm getting this in my json response

"Gallery Images": [
    "1833",
    "1834",
    "1835"
],

Those are the ID's of my custom post gallery , I need to get the URL of each ID. I did't find any solution, all images com from custom filed. My field it's called "_job_gallery_images"

Any help will be very appreciated.

Seems like I wasn't even modifying my json response because of a plugin I had activated, turning it off made me declare my meta in my functions.php file and no I have this.

` add_action('rest_api_init', 'register_custom_fields', 1, 1);

function register_custom_fields(){

  register_rest_field(
    'job_listing',
    'gallery',
    array(
      'get_callback' => 'show_image'
    )
  );

}

function show_main_image($object, $field_name, $request){
  $custom_fields = get_post_custom($object['id']);
  $main_image = $custom_fields['_job_gallery_images'];

  return $main_image;
}`

But still no luck, now the "_job_gallery_images" endpoint appears to be empty i need to response all url instead of ID

1 Answer 1

0

Have a look at wp_get_attachment_image_url for getting the URL of images: https://developer.wordpress.org/reference/functions/wp_get_attachment_image_url/

or wp_get_attachment_url for getting the URL for attachments other than images: https://developer.wordpress.org/reference/functions/wp_get_attachment_url/.

These functions return the URLs only and you could use them like so:

// your JSON
$json = '
    {
        "Gallery Images": [
            "1833",
            "1834",
            "1835"
        ]
    }
';

// convert it to PHP array
$array = get_object_vars( json_decode( $json ) );

// loop through array and get the image URLs
foreach ( $array['Gallery Images'] as $id ) {
    $image_url = wp_get_attachment_image_url( $id );
}

You could also retrieve more than just the URL, wp_get_attachment_image_src for example returns width and height of the image file as well: https://developer.wordpress.org/reference/functions/wp_get_attachment_image_src/.

1
  • Sorry not getting and also not work. can you please write full function Sep 11, 2020 at 11:54

Your Answer

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

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