Support

Account

Home Forums General Issues Add default Fields to Post programmatically

Solved

Add default Fields to Post programmatically

  • Hi!

    I have the problem that when I create a post programmatically with wp_insert_post() that my default fields that I have in a field group will not be added to the db. When I save the post in the WordPress Backend then everything that I want will be added.

    Is there a way how I can do this programmatically? I already saw alot of people that used acf_update_metadata for every single field that they want to add. My Field Group contains 120 fields with special types like Clone or Repeater. That’s not something that I would like to add step by step.

  • The only way to insert the default values into the database is to do what you describe.

    When I know that posts can be inserted in a way other than by creating a post in the admin then I plan for this ahead of time.

    There are two things that you can do. The first is that when you’re building the templates is to test for values and if there is none then to hard code the default. This can be done is several way depending on your coding style but a simple example is.

    
    if (get_field('some_field_name')) {
      // field has a value, do something
    } else {
      // field does not have a value, do default
    }
    

    Another way is to use the field key when getting a field value.

    
    $value = get_field('field_XXXXXXX');
    

    This will get the default value if there is nothing in the DB. When you use the field name ACF needs to look up the field key. If there is no value in the db for the meta value and field key reference it does not know what field you are looking for. Using the field key bypasses the need to look up the field key and allows ACF to return the default value for the field.

  • I tried something else because I don’t want to create such a big wall of code for this task.

    I have started with a empty post that is my template for this task. Then I get all the meta info with get_post_meta(template-post). Now I can add everything again to the new post that I created programmatically.

    Because I also don’t want to have a empty post inside WordPress I exported the results from get_post_meta()to a .json file. Now I use it as a template. This is my code for this task.

    
    // Insert the post into the database.
    $post = wp_insert_post( $new_post );
    //add meta template to new post
    $templateJson = json_decode( file_get_contents(get_theme_file_path('/json-templates/v1.json')));
    foreach ($templateJson As $metaKey => $metaValue) {
        $value = $metaValue[0];
        add_post_meta($post, $metaKey, $value);
    }
    
Viewing 3 posts - 1 through 3 (of 3 total)

The topic ‘Add default Fields to Post programmatically’ is closed to new replies.