I have added some text input fields to metabox in my custom post. Now whenever I put some data in those text fields in admin panel and click ‘save’, all data vanishes. Here is the code:
<?php
function swpd_render_info_fields()
{
?>
<label for="swpd_comany_addr">Company Address</label>
<input type="text" name="swpd_company_addr" id="swpd_company_addr" />
<?php
}
/* * Process the custom metabox fields */
add_action( 'save_post', 'swpd_save_info_fields',99 );
function swpd_save_info_fields($post_id) {
global $post;
if(isset($_POST['post_type']) && ($_POST['post_type'] == "swpd_directory")){
update_post_meta( $post->ID, 'swpd_company_addr', $_POST['swpd_company_addr'] );
}
}
?>
I have checked the data passed to update_post_meta() and it seems o be fine, $post->ID containes the post ID and $_POST[‘swpd_company_addr’] containes the string I want to save to meta. I really did a thorough search and none of the solutions fixes my problem. What can be wrong?
You aren’t retrieving the saved data and populating the form.
There is nothing in that function that would insert your saved data. You just write a blank form every time. You need to be conditionally populating the
input
value.I am guessing a lot at how your code works but that is the idea. You have to populate the form with existing values from the DB or you are just starting over each time.
Your custom data is deleted during autosave, because you forgot to check that. Extend your save handler:
The autosave will trigger
save_post
, but custom fields are not sent.