問題描述

當我建立一個新的帖子,剛剛點選”Add New” 後,當編輯器顯示,而不是使用下拉式清單並選擇一個自定義欄位來使用,我想要一些預設的自定義欄位輸入已經開放。

在視覺上,而不是:

我想要這樣的東西:

我知道那裡有外掛 (CPT,更多的欄位等),但我想用一個簡單的方法來做一個基本的功能。

我試過這樣的東西 (我使用自定義的帖子型別’product’):

function register_custom_fields( $post_ID ) {

    global $wpdb;

        if( !wp_is_post_revision( $post_ID ) ) {

            add_post_meta( $post_ID, 'reference', '', true);
            add_post_meta( $post_ID, 'price', '', true);

        }

}

add_action('edit_product', 'register_custom_fields');

但這似乎不起作用我認為鉤子可能是錯誤的 (因為 edit_post 在更新之後),但是我沒有看到”new post” 的任何鉤子 (在使用者點選 wp admin 中的”new post” 之後) 。有沒有 ?

或者也許整個想法是錯誤的,還有另一種方法?

最佳解決方案

在儲存時呼叫動作鉤 save_post,但是我不知道現在是否可以新增後設資料。但是在使用動作鉤 updated_post_meta 儲存帖子後,應該可以建立/更新後設資料。

EDIT

對於 pre-select 在後期建立螢幕上的一些元欄位 (自定義欄位),您必須首先新增一個空值。

如果您在檔案 wp-admin/includes/meta-boxes.php 中檢視 post_custom_meta_box()函式 (這是使用的 metabox postcustom 的回撥),可以看到該函式正在使用 list_meta()建立 pre-selected 元欄位。

現在讓我們看看程式流程,直到這個 metabox 被顯示 (我們正在尋找一個可以在這裡使用的動作/過濾器鉤子):

  1. WordPress 載入檔案 post-new.php

  2. 此檔案在 39 線上的資料庫中生成一個預設的帖子,其功能是 get_default_post_to_edit()。這很好。基本上這個帖子已經作為一個 auto-draft 在資料庫中。不幸的是,這時候沒有任何鉤子改變這些資料或新增新的東西。

  3. 作為下一步,包括檔案 edit-form-advaned.php 。該檔案將生成空洞管理頁面,幷包含基於帖子型別的 supports 引數的所有需要​​的 metaboxes 。

  4. 線上 136 包含定製欄位 metabox postcustom,並呼叫上述功能。再次,我們可以使用的動作鉤。

結論

我認為唯一的方法是使用 jQuery 或過載 postcustom metabox,並在執行 list_meta()函式之前新增元值。

例如。

add_action('admin_menu', 'wpse29358_replaceMetaBoxes'); // maybe add_meta_boxes hook
function wpse29358_replaceMetaBoxes() {
    remove_meta_box('postcustom', {POST_TYPE}, 'normal');
    add_meta_box('postcustom', __('Custom Fields'), 'wpse29358_postcustomMetabox', {POST_TYPE}, 'normal', 'core');
}

function wpse29358_postcustomMetabox($post) {
    // Add your meta data to the post with the ID $post->ID
    add_post_meta($post->ID, 'key', 'value');

    // and then copy&past the metabox content from the function post_custom_meta_box()
}

次佳解決方案

這是新增自定義欄位支援的正確方法 (編輯帖子時不會得到空白欄位)

function set_default_meta($post_ID){
    $current_field_value = get_post_meta($post_ID,'Sort Order',true);
    $default_meta = '100'; // value
    if ($current_field_value == '' && !wp_is_post_revision($post_ID)){
            add_post_meta($post_ID,'Sort Order',$default_meta,true);
    }
    return $post_ID;
}
add_action('wp_insert_post','set_default_meta');

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。