Skip to content

Instantly share code, notes, and snippets.

@rabidgadfly
Created February 12, 2016 01:47
Show Gist options
  • Select an option

  • Save rabidgadfly/2abcf2c719dd958a9386 to your computer and use it in GitHub Desktop.

Select an option

Save rabidgadfly/2abcf2c719dd958a9386 to your computer and use it in GitHub Desktop.
Methods of updating data in an advanced custom field
<?php
/*
* update a text field on the current post (using the field_name)
*/
$field_name = "text_field";
$value = "some new string";
update_field( $field_name, $value );
/*
* update a text field on the current post (using the field_key)
*/
$field_key = "field_5039a99716d1d";
$value = "some new string";
update_field( $field_key, $value );
/*
* update a checkbox field on another post
*/
$field_key = "field_5039a9973jsd1d";
$value = array("red", "blue", "yellow");
$post_id = 123;
update_field( $field_key, $value, $post_id );
/*
* add a repeater row on a taxonomy!!!
*/
$field_key = "repeater_field";
$post_id = "event_123";
$value = get_field($field_key, $post_id);
$value[] = array("sub_field_1" => "Foo", "sub_field_2" => "Bar");
update_field( $field_key, $value, $post_id );
/*
* add a flexible content row
* - each row needs an extra key "acf_fc_layout" holding the name of the layout (string)
*/
$field_key = "flexible_field";
$value = get_field($field_key);
$value[] = array("sub_field_1" => "Foo1", "sub_field_2" => "Bar1", "acf_fc_layout" => "layout_1_name");
$value[] = array("sub_field_x" => "Foo2", "sub_field_y" => "Bar2", "acf_fc_layout" => "layout_2_name");
update_field( $field_key, $value, $post_id );
/*
* Create a new post and add field data
* - if the post does not already contain a "reference" to the field object, you must use the field_key instead of the field_name.
*/
// Create post object
$my_post = array(
'post_title' => 'My post',
'post_content' => 'This is my post.',
'post_status' => 'publish',
'post_author' => 1
);
// Insert the post into the database
$post_id = wp_insert_post( $my_post );
// Add field value
update_field( "field_5039a99716d1d", "I am a value!", $post_id );
/*
* $post_id examples
*/
$post_id = null; // current post
$post_id = 1;
$post_id = "option";
$post_id = "options"; // same as above
$post_id = "category_2"; // save to a specific category
$post_id = "event_3"; // save to a specific taxonomy (this tax is called "event")
$post_id = "user_1"; // save to user (user id = 1)
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment