WordPress 的自定義字段(Custom Fields)是擴展文章、頁面等內容類型元數據的關鍵機制。其底層採用 wp_posts 主表配合 wp_postmeta 元數據表的 EAV(Entity-Attribute-Value)設計,以 post_id、meta_key、meta_value 三欄儲存靈活的鍵值對。
該函數定義於 wp-includes/post.php,用於檢索指定文章的自定義字段值。
get_post_meta( int $post_id, string $key = '', bool $single = false ): mixed
true 返回單一字串值;false(預設)返回陣列。$key 且 $single=true:返回字串(不存在則返回空字串)。$key 且 $single=false:返回陣列(不存在則返回空陣列)。$key:返回所有字段的多維陣列。$views = get_post_meta(get_the_ID(), 'views', true);
echo '瀏覽次數:' . ($views ? $views : 0);
$all_meta = get_post_meta(get_the_ID());
foreach ($all_meta as $key => $values) {
echo "$key: " . implode(', ', $values) . "
";
}
$args = [
'post_type' => 'post',
'meta_key' => 'featured',
'meta_value' => 'yes',
];
$featured_posts = new WP_Query($args);
get_post_meta() 的快取機制(內部呼叫 get_metadata() 並透過 wp_cache_get())。myplugin_)避免與主題/外掛衝突。register_meta() 註冊 show_in_rest => true 即可在區塊編輯器與 REST API 中直接讀寫。參考資源: WordPress 官方文檔 | 原文出處