2011-07-28 96 views
1

我已经添加了一些WordPress元数据代码到我的wordpress主题的functions.php,并且我面临的问题是我的metabox数据没有被保存,它只是消失在保存草稿或发布。我有一个早期版本的代码在一个月前工作得非常好,但由于一些错误,我再也没有它了,我不记得我是如何从这个草稿中获得代码的。WordPress Meta Box数据没有被保存,消失

我在此代码为今天4小时呆住了,我知道答案应该是简单的,但它会快把我逼疯了:

add_action('save_post', 'mytheme_save_data'); 

// Save data from meta box 
function mytheme_save_data($post_id) { 
    global $meta_box; 

    // verify nonce 
    if (!wp_verify_nonce($_POST['mytheme_meta_box_nonce'], basename(__FILE__))) { 
     return $post_id; 
    } 

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

    // check permissions 
    if ('page' == $_POST['post_type']) { 
     if (!current_user_can('edit_page', $post_id)) { 
      return $post_id; 
     } 
    } elseif (!current_user_can('edit_post', $post_id)) { 
     return $post_id; 
    } 

    foreach ($meta_box['fields'] as $field) { 
     $old = get_post_meta($post_id, $field['id'], true); 
     $new = $_POST[$field['id']]; 

     if ($new && $new != $old) { 
      update_post_meta($post_id, $field['id'], $new); 
     } elseif ('' == $new && $old) { 
      delete_post_meta($post_id, $field['id'], $old); 
     } 
    } 
} 

帮助,好吗?

+0

你在哪里设置了$ meta_box全局变量? – hadvig

回答

2
function save_portfolio_meta($post_id, $post) 
{ 
    if (!wp_verify_nonce($_POST['portfoliometa_noncename'], plugin_basename(__FILE__))) return $post->ID; 

    if (!current_user_can('edit_post', $post_id)) 
     return $post_id; 

    $portfolio_meta['_link'] = $_POST['_link']; 
    $portfolio_meta['_class'] = $_POST['_class']; 

    foreach($portfolio_meta as $key => $value) 
    {  
     $value = implode(',', (array)$value); 

     if (get_post_meta($post->ID, $key, FALSE)) 
     { 
     update_post_meta($post->ID, $key, $value); 
     } 
     else 
     { 
     add_post_meta($post->ID, $key, $value); 
     } 

     if (!$value) 
     delete_post_meta($post->ID, $key); 
    } 
} 

add_action('save_post', 'save_portfolio_meta', 1, 2); 
相关问题