简体   繁体   中英

How can I get data from the acf.maps field?

I tried to make a simple fetch from the Wordpress API. In this case from ACF Fields.

With the code:

I get a response. But if I try to add

${post.acf.address}

there are no data. But why, anyone who can help me?

Here is the code:

 function getPosts() { fetch( "https://localhost/wp-json/wp/v2/tourplan?per_page=100" ) .then(res => res.json()) .then(data => { let output = '<h2 class="mb-4">Posts</h2>'; data.forEach(function(post) { output += ` <div class="card card-body mb-3"> <h2>${post.acf.location}</h3> <h3>${post.acf.programmname}</h3> <p>${post.acf.datum}</p> <p>${post.acf.beginn}</p> </div> `; console.log(data); }); document.getElementById("output").innerHTML = output; }); } 

This is the json response if you call the fetch url in a browser.

 [ { "id": 5692, "date": "2019-05-08T14:41:15", "date_gmt": "2019-05-08T12:41:15", "guid": { "rendered": "https://localhost/?post_type=tourplan&#038;p=5692" }, "modified": "2019-05-08T14:41:15", "modified_gmt": "2019-05-08T12:41:15", "slug": "münchen", "status": "publish", "type": "tourplan", "link": "https://localhost/Tourplan/münchen/", "title": { "rendered": "München" }, "content": { "rendered": "", "protected": false }, "template": "", "authorName": "wtced", "acf": { "plz": "81825", "location": "Wirtshaus", "programmname": "\\"Programmname\\"", "datum": "20190913", "einlass": "18:00", "beginn": "20:00", "ticketlink": "https://localhost/hxanh/", "ausverkauft": false, "vvk": "Veranstalter: Testverein eV", "zusatzfeld": "", "maps": { "address": "Feldstraße 35, 81825 München, Deutschland", "lat": "48.386076050384", "lng": "11.348405060504" } } ] 

The address property is inside the maps property ${post.acf.maps.address}

Not every post object have maps property so you will need to check if that field exists

data.forEach(function({ acf }) {
  output += `
    <div class="card card-body mb-3">
      <h2>${acf.location}</h3>
      <h3>${acf.programmname}</h3>
      <p>Open Doors: ${acf.einlass}</p>
      <p>Start at: ${acf.beginn}</p>
      <p>${acf.maps && acf.maps.address ? acf.maps.address : 'No address found'}</p>
    </div>
  `;
});

Thank you all, the code was okay. The reason for doesn't work were too many results.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM