0

I have a problem with ACF plugin.

function add_custom_post(/* .. */){}
     $post_id = wp_insert_post(array(
      //....
   ));

   update_field('fieldname', $value, $post_id);

   return (bool)$post_id;
}

Symptoms: <?php the_field('fieldname'); ?> does not return value in template; Fields are saved and values are visible in wp-admin. After clicking "Update" to post, above starts working fine.
From what I noticed it does not create post key if I use Update field and backoffice save creates them.

How to add value programmatically to newly added post?

EDIT:
It would seem like i have to create key for field in post. No idea how.

0

3 Answers 3

3

You can do this instead of using update_field():

update_post_meta($post_id, 'fieldname', $value);
update_post_meta($post_id, '_fieldname', 'field_' . uniqid()); // `uniqid() is a native PHP function. This is also how ACF creates the field keys

Also, depending where you are retrieving the value, you may also have to pass the post id.

the_field('fieldname', $post_id);
4
  • Testing it atm!. I'm retrieving in theloop.
    – Grzegorz
    Dec 1, 2016 at 8:52
  • Does not work. Still values are not retrieved. But are visible in wp-admin. Still need to re-save product in admin, to make them visible
    – Grzegorz
    Dec 1, 2016 at 8:59
  • Ok. Maybe then you need to go through this process - advancedcustomfields.com/resources/register-fields-via-php
    – Dan.
    Dec 1, 2016 at 9:03
  • Or, just use get_post_meta()
    – Dan.
    Dec 1, 2016 at 9:03
1

I ended up with following, which works for me:

function edu_acf_getValue($fieldname, $post_id = false){
    if($post_id === false) $post_id = get_the_ID ();
    if(($value = get_field($fieldname, $post_id)))
        return $value;
    $value = get_post_meta($post_id, $fieldname);
    return $value[0];
}
function edu_acf_updateValue($fieldname, $value, $post_id){
    $field_key = 'field_' . uniqid();
    update_post_meta($post_id, $fieldname, $value);
    update_post_meta($post_id, '_'.$fieldname, $field_key);
    update_field($field_key, $value, $post_id);
}
1
  • How could I use this with repeater fields?
    – J Robz
    Apr 29, 2019 at 22:02
0

use following to retrieve ACF field values:

    get_field('fieldname',$post_id);
1
  • Does not work if post was not added via wp-admin
    – Grzegorz
    Dec 1, 2016 at 9:29

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