2011-11-04 176 views
9

我創建了一個自定義後類型顯示自定義的數據。它將在Wordpress儀表板中加載得很好,我也可以保存它。現在讓我們假設這是一個自定義帖子類型,它包含幾個字符串和幾個日期的數據。如何從自定義文章類型

我希望能夠檢索這些自定義文章類型(我已經使用WP_Query並指定post_type到我的自定義後類型的名稱一樣)。當我在返回的對象上調用print_r時,對象中無處存儲自定義數據(字符串和日期)。我將如何從數據庫中檢索這些數據?

我已經看了好幾個小時,並沒有發現任何的方法來獲取這些數據。

按照要求:這是數據的存儲方式:

function update_obituary(){ 
    global $post; 
    update_post_meta($post->ID, "first_name", $_POST["first_name"]); 
    update_post_meta($post->ID, "last_name", $_POST["last_name"]); 
    update_post_meta($post->ID, "birth_date", $_POST["birth_date"]); 
    update_post_meta($post->ID, "death_date", $_POST["death_date"]); 
    update_post_meta($post->ID, "publication_date", $_POST["publication_date"]); 
} 

該功能被綁定到「save_post」鉤。當我在編輯模式下重新打開自定義帖子類型實例時,數據將被重新顯示。這意味着它存儲在數據庫中,對吧?

+0

請添加一些代碼。額外的元數據如何存儲? –

+0

按要求添加了代碼。 – Prusprus

回答

9

如果編輯類型的職位時元數據顯示出來,那麼,它必須已成功存儲在數據庫中。

有兩個wp函數來檢索自定義帖子類型的元數據:get_post_custom_valuesget_post_meta。區別在於,get_post_custom_values可以訪問非唯一的自定義字段,即具有與單個鍵相關聯的多個值的那些字段。你也可以選擇將它用於獨特的領域 - 品味問題。

假設,你的職位類型被稱爲「訃告」:

// First lets set some arguments for the query: 
// Optionally, those could of course go directly into the query, 
// especially, if you have no others but post type. 
$args = array(
    'post_type' => 'obituary', 
    'posts_per_page' => 5 
    // Several more arguments could go here. Last one without a comma. 
); 

// Query the posts: 
$obituary_query = new WP_Query($args); 

// Loop through the obituaries: 
while ($obituary_query->have_posts()) : $obituary_query->the_post(); 
    // Echo some markup 
    echo '<p>'; 
    // As with regular posts, you can use all normal display functions, such as 
    the_title(); 
    // Within the loop, you can access custom fields like so: 
    echo get_post_meta($post->ID, 'birth_date', true); 
    // Or like so: 
    $birth_date = get_post_custom_values('birth_date'); 
    echo $birth_date[0]; 
    echo '</p>'; // Markup closing tags. 
endwhile; 

// Reset Post Data 
wp_reset_postdata(); 

注意的一點是,爲了避免混淆: 在get_post_meta離開了布爾將使它返回一個數組,而不是字符串。 get_post_custom_values總是返回一個數組,這就是爲什麼在上面的例子中,我們回顯了$birth_date[0]而不是$birth_date

而且我不是此刻的100%確定,預期在上述$post->ID是否會奏效。如果不是,請用get_the_ID()替換它。兩者都應該工作,肯定會有。可以測試一下,但節省了我自己的時間...

爲了完整起見,請檢查WP_Query的codex以獲取更多查詢參數和正確的用法。

+0

謝謝!這很棒!希望像我這樣的人卡住試圖找到信息將落在這個頁面:) – Prusprus

+0

不錯!很好奇如何做到這一點我自己,非常有幫助的答案 – Alex

+0

感到驚訝的是得到一個約會超過5年回答的評論。雖然再次閱讀,但WP API的這一部分並沒有太大改變 - 這些信息確實仍然適用。 –

相關問題