0

I'm trying to create a custom meta box to save a short post summary for a theme.

I've created the metabox which displays as expected on the post admin page. When the post is saved, the text from the meta box is not being saved. I've looked at the wp_postmeta table and see no additions.

Can anyone shed any light on this for me?

Thanks

function smry_custom_meta(){

    $postTypes = array('post', 'portfolio');

    foreach ($postTypes as $postType) {
        add_meta_box(
            'summary-meta-box', // id
            __('Post Summary'), // title
            'smry_show_meta_box', // callback
            $postType, // post type
            'normal' // position
            );
    }
}
add_action('add_meta_boxes', 'smry_custom_meta');

function smry_show_meta_box(){

    global $post;
    $meta = get_post_meta($post->ID, 'smry_text', true);

    <p>
        <label>Summary Text</label>
        <textarea name="smry_text" id="smry_text" cols="60" rows="5">
            <?php echo $meta; ?>
        </textarea>
    </p>
    <?php
}

function save_summary_meta(){

    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE){
        return $post_id;
    }

    $new = $_POST["smry_text"];

    update_post_meta($post_id, 'smry_text', $new);
}
add_action('save_post', 'save_summary_meta');
tonyedwardspz
  • 1,519
  • 2
  • 20
  • 43

1 Answers1

0

I think your problem could use your use of $post_id inside save_summary_meta(). Try this instead:

function save_summary_meta(){
    global $post;

    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE){
        return $post->ID;
    }

    $new = $_POST["smry_text"];

    update_post_meta($post->ID, 'smry_text', $new);
}
add_action('save_post', 'save_summary_meta');
henrywright
  • 9,235
  • 22
  • 77
  • 139
  • Perfect. Out of interest, is the preferred method of accessing $post values using the global $post? Is there any difference between that and simply passing $post_id into the function? – tonyedwardspz Sep 02 '14 at 16:41
  • It might be worth taking a look at [this question](http://stackoverflow.com/questions/1557787/are-global-variables-in-php-considered-bad-practice-if-so-why) and [this answer](http://stackoverflow.com/a/1557799/1709033). My own personal approach would be to use a global if it streamlines code but if a variable is easily passed into a function I'd do that instead. – henrywright Sep 02 '14 at 16:48