2014-09-02 58 views
0

我正在嘗試創建自定義元框以保存主題的簡短髮布摘要。WP自定義元框未保存

我已經創建了metabox,它按照預期顯示在帖子管理頁面上。保存帖子後,元框中的文本不會被保存。我看了一下wp_postmeta表,看到沒有增加。

任何人都可以爲我闡明這一點嗎?

感謝

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'); 
+1

'save_summary_meta()'裏面,使用'$ post_id'。你從哪裏得到這個變量? – henrywright 2014-09-02 16:30:44

+0

就是這樣。我忘了將它傳遞給函數。感謝您指出:-) – tonyedwardspz 2014-09-02 16:34:28

回答

0

我認爲你的問題可以用你的$post_id使用內部save_summary_meta()。試試這個:

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'); 
+0

完美。出於興趣,是使用全局$ post訪問$ post值的首選方法嗎?這與僅僅將$ post_id傳遞給函數有什麼區別嗎? – tonyedwardspz 2014-09-02 16:41:27

+0

這可能是值得看看[這個問題](http://stackoverflow.com/questions/1557787/are-global-variables-in-php-considered-bad-practice-if-so-why)和[這個答案](http://stackoverflow.com/a/1557799/1709033)。我個人的方法是使用全局的,如果它簡化代碼,但如果一個變量很容易傳遞到一個函數,我會這樣做。 – henrywright 2014-09-02 16:48:24

+0

謝謝,我會讀一讀。 – tonyedwardspz 2014-09-02 16:50:14