問題描述
好的,所以我已經註冊了一些自定義帖子型別和一些分類。現在,對於我的生活,我無法找出我需要新增一個自定義欄位到我的自定義帖子型別的程式碼。
我需要一個下拉選單和一行文字區域。但是我也需要為 Post 型別分隔欄位。所以說,帖子型別有一個有 3 個欄位,而帖子型別 2 有 4 個欄位,但欄位是不同的。
任何提示都可以幫助我檢視該抄本,並發現了一些東西,但是無法理解我需要新增到我的 functions.php 檔案
最佳解決方案
這可能比你想象的更復雜,我會研究一下框架:
如果你想寫自己的,這裡有一些體面的教程:
-
http://net.tutsplus.com/tutorials/wordpress/creating-custom-fields-for-attachments-in-wordpress/
-
http://sltaylor.co.uk/blog/control-your-own-wordpress-custom-fields/
-
http://thinkvitamin.com/code/create-your-first-wordpress-custom-post-type/
次佳解決方案
新增/編輯 supports 引數 (使用 register_post_type 時) 將 custom-fields 包含到您自定義帖子型別的後期編輯螢幕中:
'supports' => array(
'title',
'editor',
'excerpt',
'thumbnail',
'custom-fields',
'revisions'
)
第三種解決方案
雖然您應該新增一些驗證,但是對於當前版本的 WordPress,此操作似乎並不複雜。
基本上您需要兩個步驟來將自定義欄位新增到自定義帖子型別中:
-
建立一個儲存你的自定義欄位的 metabox
-
將您的自定義欄位儲存到資料庫
這些步驟在這裡全面描述:http://wordpress.org/support/topic/is-it-possible-to-add-an-extra-field-to-a-custom-post-type
例:
將稱為”function” 的自定義欄位新增到名為”prefix-teammembers” 的自定義帖子型別。
首先新增 metabox:
function prefix_teammembers_metaboxes( ) {
global $wp_meta_boxes;
add_meta_box('postfunctiondiv', __('Function'), 'prefix_teammembers_metaboxes_html', 'prefix_teammembers', 'normal', 'high');
}
add_action( 'add_meta_boxes_prefix-teammembers', 'prefix_teammembers_metaboxes' );
如果您新增或編輯”prefix-teammembers” add_meta_boxes_{custom_post_type}鉤子被觸發。有關 add_meta_box()功能,請參閱 http://codex.wordpress.org/Function_Reference/add_meta_box 。在上面呼叫 add_meta_box()是 prefix_teammembers_metaboxes_html,一個回撥來新增你的表單域:
function prefix_teammembers_metaboxes_html()
{
global $post;
$custom = get_post_custom($post->ID);
$function = isset($custom["function"][0])?$custom["function"][0]:'';
?>
<label>Function:</label><input name="function" value="<?php echo $function; ?>">
<?php
}
在第二步中,您將自定義欄位新增到資料庫。在儲存 save_post_{custom_post_type}鉤子被觸發 (從 3.7 版,參見:https://stackoverflow.com/questions/5151409/wordpress-save-post-action-for-custom-posts) 。您可以勾選此選項來儲存您的自定義欄位:
function prefix_teammembers_save_post()
{
if(empty($_POST)) return; //why is prefix_teammembers_save_post triggered by add new?
global $post;
update_post_meta($post->ID, "function", $_POST["function"]);
}
add_action( 'save_post_prefix-teammembers', 'prefix_teammembers_save_post' );
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。