Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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?

share|improve this question
    
Does it work outside the conditional? Please also check if your Action is really called - maybe put a wp_die in there just to be sure. –  fischi Dec 29 '12 at 18:33

2 Answers 2

up vote 0 down vote accepted

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.

share|improve this answer
    
This was so obvious! After sitting to much time in foront of PC I could not find it. Thanks! –  HoGo Dec 29 '12 at 18:06

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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