0

When in wp-admin I want to manipulate one value of an array and then update the post_meta with this array. My array looks like this:

1285
array(1) {
  [0]=>
  array(2) {
    ["description"]=>
    string(26) "description text goes here"
    ["food"]=>
    string(3) "Yes"
  }
}

Here 'description' and 'food' are custom fields. What I want to do is manipulate the value of 'description'. Instead of using the value of the custom field 'description', I would like to replace it with the post_content (the_content();). The rest of the fields (in this case just 'food') I want to update with the actual value of the custom field.

Now, I know that the code below should update the post_meta with the actual custom field values, but how can i manipulate one of them as mentioned above?

function cf_description_to_content($post_ID){
$array = $_POST['wiloke_listgo_my_custom_fields'];
update_post_meta( $post_ID, 'wiloke_listgo_my_custom_fields', $array ); 
}
add_action('save_post', 'cf_description_to_content', 100, 1);
1

Try this code:

 
function cf_description_to_content($post_ID){
    $data = get_post_meta( $post_ID, 'wiloke_listgo_my_custom_fields', true );
    // Put whatver description you want assign to the description field
    $data['description'] = $_POST['wiloke_listgo_my_custom_fields'];
    update_post_meta( $post_ID, 'wiloke_listgo_my_custom_fields', $data ); 
}
add_action('save_post', 'cf_description_to_content', 100, 1); 

  • Awesome, thanks! Please tell me; why use ,true in get_post_meta? – RobbTe Jul 20 '18 at 12:58
  • For more information, visit WordPress official site: developer.wordpress.org/reference/functions/get_post_meta – Baikare Sandeep Jul 20 '18 at 13:12
  • 1
    The get_post_meta function receive the the third parameter as (boolean) (optional) If set to true then the function will return a single result, as a string. If false, or not set, then the function returns an array of the custom fields. This may not be intuitive in the context of serialized arrays. If you fetch a serialized array with this method you want $single to be true to actually get an unserialized array back. If you pass in false, or leave it out, you will have an array of one, and the value at index 0 will be the serialized string. Default: false – Baikare Sandeep Jul 20 '18 at 13:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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