Support

Account

Home Forums General Issues New Field – Auto Update posts in custom post type

Solved

New Field – Auto Update posts in custom post type

  • I created a new field for a custom post type with a default value. I know the posts all need to be “updated” to receive that default value. Is this the way to do it?

    $args = array(
      'post_type'   => 'book'
    );
     
    $all_books = get_posts( $args );
    update_field($selector, $value, $all_books);

    I don’t want to open the 1000+ posts and click the update button 😉

  • You need to loop through the posts and update the field, yes you could do that.

    
    get posts
    while have posts
    the post
    update value
    

    But I wouldn’t.

    The best way to do this is to check the value where it is used and substitute a default value if it’s not set, it only takes a couple lines of code to deal with it.

    
    $value = get_field('your-new-field');
    if (!$value) {
      $value = 'the default value';
    }
    // do something with value
    

    you could also add an acf/load_value filter for the field in question that sets the default value if it is empty https://www.advancedcustomfields.com/resources/acf-load_value/

  • I am considering using acf/load_value/key={$field_key} are all the parameters required? So do I still need to loop through each post in the custom post type?

  • Answered my own question… Yes it in necessary.

  • @hube2 actually I am finding that though it does “load and save” the correct data to the database, it seems as if the post isn’t actually “updated”. Without updating I am not able to use the column filtering in the backend for that field. Only once I actually update the post does then that data become filterable.

  • Yes, because the value is not updated, you’re just inserting a default.

    To make the filtering work you will need to create a temporary function that queries the posts, loops through them and updates each value.

    You have a lot of posts and this could time out.

    I would add a meta query to my WP_Query to only get posts where this custom field does not exist, this way you will only update posts that have not value. If it times out the first time you can just keep re-loading the page until they are all updated. https://codex.wordpress.org/Class_Reference/WP_Query#Custom_Field_Parameters

Viewing 6 posts - 1 through 6 (of 6 total)

The topic ‘New Field – Auto Update posts in custom post type’ is closed to new replies.