2013-04-29 32 views
0

我正在使用wp_update_post以編程方式爲前端的帖子添加標題和標籤。我遇到了流程中的自定義字段的一個令人頭痛的問題:當最初創建文章時創建和填充的兩個自定義字段中的一個已刪除其值,而另一個完全正確。wp_update_post上正在丟失的Wordpress自定義字段,帶有扭曲

這是代碼的一部分,我用它來創建擺在首位的帖子:

// Set the post ID so that we know the post was created successfully 
$post_id = wp_insert_post(
    array(
     'comment_status'=> 'closed', 
     'ping_status' => 'closed', 
     'post_author' => $author_id, 
     'post_name'  => $slug, 
     'post_status' => 'publish', 
     'post_type'  => 'custom' 
    ) 
); 

// If the post was created properly 
if($post_id) { 

    // Add meta/custom field data to post 
    add_post_meta($post_id, 'custom_random_id', $randomId); 
    add_post_meta($post_id, 'viewcount', '1'); 

然後,這是我使用更新的標題和標籤的代碼:

// Continue if untampered 
if($new_hashed_value == $_POST['hash']) { 

    $updatePost = array(); 
    $updatePost['ID'] = $post_id; 
    $updatePost['post_title'] = $title; 
    $updatePost['tags_input'] = $tags; 

    if(wp_update_post($updatePost)) { 

     totallyUnrelatedStuff(); 
    } 

我從other posts瞭解到wp_update_post可能會刪除值 - 但在這種情況下,自定義字段'custom_random_id'始終保持不變,'viewcount'總是有它s值被刪除。

我試圖改變它,讓它去:

if(wp_update_post($updatePost)) { 

     update_post_meta($post_id, 'viewcount', '1'); 
    } 

甚至:

if(wp_update_post($updatePost)) { 
     delete_post_meta($post_id, 'viewcount');          
     add_post_meta($post_id, 'viewcount', '1'); 
    } 

觀看次數字段的值繼續被刪除。

此外,剛剛拋出另一個扳手我,

if(wp_update_post($updatePost)) { 
     delete_post_meta($post_id, 'viewcount');          
     add_post_meta($post_id, 'new_field', 'new_value'); 
    } 

完美。

有人會知道發生了什麼事嗎?

謝謝!

+0

你使用任何插件緩存? – doublesharp 2013-04-29 15:53:49

回答

2

我發生過類似的事情。

wp_update_post調用動作save_post。由於您使用的是自定義帖子類型,因此您可能需要在save_post操作上運行自定義功能才能保存元數據。

問題是當您撥打wp_update_post您的用於保存元數據的自定義功能是將這些值設置爲空白,因爲它找不到要查找的數據(通常位於$_POST)。

您需要添加一些額外的檢查來查看您的save_post動作函數是否應該運行,以某種方式測試以查看它是從Wordpress中的編輯屏幕調用還是從前端表單調用。

在我的情況下,這解決了這個問題:

function save_metadata($postid) { 
    global $post; 
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return false; 
    if (!current_user_can('edit_page', $post->ID)) return false; 
    if (empty($post->ID) || get_post_type($post->ID) != 'post_type_here') return false; 
    if (!is_admin()) return false; 

    updateMyMetas(); 
} 
+0

另一種選擇是在函數save_post回調函數中的'update_user_meta()'調用之前檢查'if(isset($ _ POST ['custom_random_id']))''。 – strangerstudios 2014-04-21 15:13:05