I’m getting objects from a 3rd party API and creating a post for each one of them.
Two post types are created object
and aruodas-object
(the 3rd party API object type). There is a field group object
with all the custom fields for the object
and a field group aruodas
for some additional custom values for the 3rd party objects.
I have this code in my functions.php
$ad = array('post_type' => 'aruodas-object', 'post_status' => 'publish');
switch($ads[0]['objTypeId']){
case '1':
$ad['post_id'] = $ads[0]['Id'];
$ad['post_title'] = $ads[0]['addressLong'];
$ad['post_excerpt'] = $ads[0]['addressLong'];
$ad['post_date'] = $ads[0]['AddExpDate'];
$ad['post_date_gmt'] = get_gmt_from_date($ads[0]['AddExpDate']);
$ad['post_author'] = get_users(array('nicename' => substr($ads[0]['notes'], -6), 'fields' => 'ID'))[0];
//Custom
$ad['object_parduotas'] = $ads[0]['Sold'];
$ad['object_tipas'] = 'butas';
$ad['object_veiksmas'] = 'Pardavimui';
...
break;
default:
break;
}
$existing_post = get_page_by_title($ad['post_title'], OBJECT, 'aruodas-object');
if (null === $existing_post) {
$id = wp_insert_post($ad);
foreach($ad as $key => $value){
if(str_starts_with($key, 'object_')){
update_field($key, $value, $id);
}
}
//3rd party only fields from different group
update_field('nuotraukos', array_map(function($url){return ['url' => $url];}, $ad['nuotraukos']), $id);
update_field('thumbnail', $ad['thumbnail'], $id);
}
The post is successfully created and values inserted, but in page-objektai.php
the get_field()
returns null
until I go to the newly created post and update it, then it works as expected.
<?php while ( $result->have_posts() ) : $result->the_post(); ?>
<?php $objectData = get_field('object');
// if(!$objectData) return;
switch($objectData['objekto_tipas']){
...
?>
//HTML card
?>
I thought it might be a problem with the cache, but any of the solutions I found didn’t help, also using field values for the key in update_field()
doesn’t even insert the values in the field when the post is created.
2
Answers
Solution:
First of all, to save a new post use
field_key
in theupdate_field()
.In my case, I had field group
object
and in it a group fieldobject
which acts as a repeater field. To access it I always useobject_{field_name}
, but for insertion, you can't just specify the key for each field in the group field, you have to pass an array offield_key => value
.I changed the $ad array to
And the insertion loop was changed to this:
Hi I think you can try………
$objectData = get_field(‘object’, get_the_ID());
It might be fix your issue