2014-01-24 15 views
0

我試圖做一個函數,其中某個帖子類型的子帖子繼承了它的父類相同的標題和slu g。我正在使用WP類型來定義我的帖子類型及其關係。但我在與下面的代碼的麻煩:如何在插入時獲得一些帖子元數據?

function copy_parent_post_title($post_id) { 

    $new_post = get_post($post_id); 

    if($new_post->post_type == 'carnews-adverts') { 

     $parent_id = get_post_meta($post_id, '_wpcf_belongs_carnews_id', true); 
     $parent_title = get_the_title($parent_id); 
     $post_slug = sanitize_title_with_dashes($parent_title); 

     $post_update = array(
      'ID'   => $post_id, 
      'post_title' => $parent_title, 
      'post_name' => $post_slug 
     ); 

     remove_action('wp_insert_post', 'copy_parent_post_title'); 
     wp_update_post($post_update); 
     add_action('wp_insert_post', 'copy_parent_post_title'); 

    } 

} 
add_action('wp_insert_post', 'copy_parent_post_title'); 

的問題是這一行:

$parent_id = get_post_meta($post_id, '_wpcf_belongs_carnews_id', true); 

我相信這是因爲在該點後的元數據尚未插入數據庫沒有?如果是的話,插入帖子後如何通過訪問get_post_meta來實現我想要的功能?

感謝

+0

爲什麼不能'$ parent_title = get_the_title($ post_id);'或'$ parent_title = $ new_post-> post_title;'? 是不是$ post_id父郵件的ID? – Hamish

+0

不,$ post_id是插入的當前帖子,它不是父帖子。 – user1280853

+0

我認爲要訪問開始由WP類型添加的'_wpcf_belongs_carnews_id',您需要查看$ _POST數組。 – Hamish

回答

0

我認爲訪問是由WP類型添加了「_wpcf_belongs_carnews_id」,你需要的$ _POST數組中的樣子。但是,WP類型可能在調用wp_insert_post()後調用add_post_meta()。在這種情況下,如果掛鉤到wp_insert_post中,元數據將不會出現。

相反,勾你的函數到add_post_meta:

function copy_parent_post_title($post_id, $meta_key, $meta_value) { 

    $new_post = get_post($post_id); 

    if (($new_post->post_type == 'carnews-adverts') && 
     ($meta_key == '_wpcf_belongs_carnews_id')) { 

     $parent_id = $meta_value; 

     $parent_title = get_the_title($parent_id); 

     // ... Rest of your function 
    } 
} 
add_action('add_post_meta', 'copy_parent_post_title', 10, 3); 

這可能是完全錯誤的,因爲我幾乎永遠使用WordPress。