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?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
You aren’t retrieving the saved data and populating the form.
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
}
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.
function swpd_render_info_fields($post)
{
$meta = get_post_meta($post->ID);
$value = (!empty($meta['swpd_company_addr']))
? $meta['swpd_company_addr']
: '';
?>
<label for="swpd_comany_addr">Company Address</label>
<input type="text" name="swpd_company_addr" id="swpd_company_addr" value="<?php echo $value ?>" />
<?php
}
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.
Method 2
Your custom data is deleted during autosave, because you forgot to check that. Extend your save handler:
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
return;
The autosave will trigger save_post, but custom fields are not sent.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0