問題描述

我正在使用*_add_form_fields 操作將字段添加到自定義分類。其中一個字段是 wp_editor() 。

我所面臨的問題是當我在頁面上輸出 WordPress 編輯器時:

wp_editor('test', 'mydescription', array('textarea_name' => 'my_description'));

然後如果我點擊頁面上的編輯器,並將默認值從 test 更改為 something else,則 $_POST['my_description']變量仍設置為 test

我應該添加一個額外的設置給我的編輯器嗎?有沒有理由為什麼我不能改變 textarea 的價值?

編輯

下面是一個非常簡單的測試用例,顯示了這種情況。將它放在你的 functions.php 文件中,然後創建一個新的標籤。 ‘my_description’ 的發佈值不會改變。

class Test{

    function __construct() {

        add_action('add_tag_form_fields', array($this, 'add_tag_form_fields'));

        add_action('created_term', array($this, 'created_term'));
    }

    function add_tag_form_fields($tag){

        if ( current_user_can( 'publish_posts' ) ): ?>

        <div class="form-field">
            <?php wp_editor('test', 'mydescription', array('textarea_name' => 'my_description')); ?>
        </div>

        <?php
    }

    function created_term($tag){
        echo '<pre>';
        print_r($_POST);
        echo '</pre>';
            die();
    }
}
new Test();

編輯

這僅在附加到”created_term” 操作時發生。如果你附加到”edited_terms” 它按預期工作,我認為這是在創建術語頁面上使用 ajax 的結果… 我已經更新了測試代碼來顯示這個。

最佳解決方案

tinyMCE <textarea> 元素最初被使用的 serialize 函數看不到:

$.post(
    ajaxurl,
    $('#addtag').serialize(), function(r) {
        // Content here.
    }
});

您將需要調用 tinyMCE.triggerSave()使其可見。

下面是一個簡單的代碼段,應該做的訣竅:

jQuery('#submit').mousedown( function() {
    tinyMCE.triggerSave();
});

這在一個外部文件中,以 wp_enqueue_script()入隊; 它用於我進行的測試。

次佳解決方案

在您的 edited_terms 功能中,您需要保存該值,並在 add_tag_form_fields 中,您需要使用保存的數據替換 test

就像是:

class Test{

    function __construct() {

        //do_action('add_tag_form_fields', $taxonomy);
        add_action('add_tag_form_fields', array($this, 'add_tag_form_fields'));

        //do_action("edited_terms", $term_id, $tt_id, $taxonomy);
        add_action('edited_terms', array($this, 'edited_terms'));
    }

    function add_tag_form_fields($term){

        if ( current_user_can( 'publish_posts' ) ): ?>

        <div class="form-field">
            <?php
            $saved = get_option('termmeta_'.$term->term_id);
            $saved = (empty($saved))? 'test': $saved;
            wp_editor($saved, 'mydescription', array('textarea_name' => 'my_description')); ?>
        </div>

        <?php
    }

    function edited_terms($term_id){
        if (isset($_POST['mydescription'])){
            update_option('termmeta_'.$term_id,$_POST['mydescription']);
        }
    }
}
new Test();

現在,如果你想要一個更簡單的方法,添加所有類型的額外的字段到你的標籤/類別或自定義分類編輯表單,而不需要重新發明輪子看看 TAX Meta Class

參考文獻

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