1

I am trying to create a REST api get to fetch projects and return them as JSON. I am trying to create a new endpoint, where I am trying to fetch the CPT and the other Advanced Custom Fields.

So far I can retrieve all posts from my custom post type but I would like to get the ACF (fields) as well.

function ldl_get_projects( $data ) {
  $posts = get_posts([
    'post_type'         => 'maps_projects',
    'post_status'       => 'publish',
    'posts_per_page'    => -1,
  ]);

  if (empty( $posts ) ) {
    return null;
  }

  $data = [];

  foreach ($posts as $post) {
    $api_content = [
        'name'  => $post->post_title,
        'description'  // ACF
        'cargo'  => // ACF 
        'services'  =>  // ACF
        'origin'  => // ACF
        'destination'  =>  // ACF
        'specifics'  =>  // ACF
        'long'  => // ACF
        'lat'  => // ACF
        'gallery'  => // ACF
    ];
    $data[] = $api_content;
  }

  return $data;
}

As you can see, the fields marked with // ACF need to fetch the ACF field. Can someone assist me a little further with this?

Thanks.

1 Answer 1

2

Advanced custom fields uses get_field() function to retrieve the fields. So, all you have to do is to retrieve them by using:

$field = get_field('field_name', $post->ID, 'format_value');

for each of your fields in the loop. You can read this page for more information.

Questions about plugins are off-topic here, That's why your question haven't receive much attention in 4 days. But since it was a simple problem i posted the answer.

1
  • How we could retrieve the post via WP REST in first place using ACF though? Cause if I understand correctly the ACF DOC the get_field( ) functon does not grab it from WP REST, right? May 31, 2020 at 18:36

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.