web-dev-qa-db-fra.com

Charger tinyMCE/wp_editor () via AJAX

Duplicate possible:
Comment charger wp_editor () via AJAX/jQuery

Il y a plusieurs questions à ce sujet ( comme ceci , ou cela ), mais aucune d’entre elles ne me fournit de solution.

La situation: j'ai un metabox. Dans cette metabox, je souhaite ajouter dynamiquement des éditeurs tinyMCE.

Le code:

PHP:

add_action('wp_ajax_insert_tinymce', 'insert_tinymce');
function insert_tinymce(){
    wp_editor('','editor-id');
    exit;
}

JS:

$.post(
    global.ajaxurl,
    {
        action : 'insert_tinymce'
    },
    function(response) {

        $(response).appendTo('#target-div');

        console.log(tinyMCE); // no instance of 'editor-id'
        console.log(tinyMCEPreInit.mceInit); // 'editor-id' not listed
        console.log(tinyMCE.activeEditor); // null
    }
);

Le résultat est une fenêtre d'éditeur (avec onglets html et visuels), un bouton de téléchargement et une zone de texte mais totalement sans boutons.

Ce que j'ai essayé (comme suggéré dans les autres questions):

// In the response function
tinyMCE.init({
    skin : "wp_theme",
    mode : "exact",
    elements : "editor-id",
    theme: "advanced"
});


// In the response function
tinyMCE.init(tinyMCEPreInit.mceInit['editor-id']);


// in the PHP
ob_start();
wp_editor( '', 'editor-id' );
echo ob_get_clean();

Ce premier fonctionne, mais je devrais définir de nombreux paramètres manuellement, plus mes boutons personnalisés n'apparaissent pas.

Le second ne fonctionne évidemment pas, car il n'y a pas de editor-id dans tinyMCEPreInit.mceInit

Le troisième (tampon de sortie) ne fait aucune différence.


J'ai remarqué que wp_editor() ajoute les instances tinyMCE à tinyMCEPreInit et l'ajoute via le hook admin_print_footer_scripts. Il me faudrait donc mettre à jour dynamiquement tinyMCEPreInit (sans perdre l’instance de l’éditeur principal), puis déclencher tinyMCE.init(tinyMCEPreInit.mceInit['editor-id']) -PEUT-ÊTRE

Toute aide très appréciée ;-)

Merci!

4
xsonic

votre message ici m'a aidé à trouver une solution. Parallèlement à la propriété mceInit, je devais également récupérer le qtInit généré par wp_editor.

Ce qui suit est le code pertinent dans ma classe. En gros, j'ai wp_editor lancé pour que le javascript soit généré. J'utilise des points d'ancrage pour récupérer le javascript afin de pouvoir le répercuter dans la réponse ajax.

// ajax call to get wp_editor
add_action( 'wp_ajax_wp_editor_box_editor_html', 'wp_editor_box::editor_html' );
add_action( 'wp_ajax_nopriv_wp_editor_box_editor_html', 'wp_editor_box::editor_html' );

// used to capture javascript settings generated by the editor
add_filter( 'tiny_mce_before_init', 'wp_editor_box::tiny_mce_before_init', 10, 2 );
add_filter( 'quicktags_settings', 'wp_editor_box::quicktags_settings', 10, 2 );

class wp_editor_box {

    /*
    * AJAX Call Used to Generate the WP Editor
    */

    public static function editor_html() {
        $content = stripslashes( $_POST['content'] );
        wp_editor($content, $_POST['id'], array(
            'textarea_name' => $_POST['textarea_name']
        ) );
        $mce_init = self::get_mce_init($_POST['id']);
        $qt_init = self::get_qt_init($_POST['id']); ?>
        <script type="text/javascript">
            tinyMCEPreInit.mceInit = jQuery.extend( tinyMCEPreInit.mceInit, <?php echo $mce_init ?>);
            tinyMCEPreInit.qtInit = jQuery.extend( tinyMCEPreInit.qtInit, <?php echo $qt_init ?>);
        </script>
        <?php
        die();
    }

    /*
    * Used to retrieve the javascript settings that the editor generates
    */

    private static $mce_settings = null;
    private static $qt_settings = null;

    public static function quicktags_settings( $qtInit, $editor_id ) {
        self::$qt_settings = $qtInit;
                    return $qtInit;
    }

    public static function tiny_mce_before_init( $mceInit, $editor_id ) {
        self::$mce_settings = $mceInit;
                    return $mceInit;
    }

    /*
    * Code coppied from _WP_Editors class (modified a little)
    */
    private function get_qt_init($editor_id) {
        if ( !empty(self::$qt_settings) ) {
            $options = self::_parse_init( self::$qt_settings );
            $qtInit .= "'$editor_id':{$options},";
            $qtInit = '{' . trim($qtInit, ',') . '}';
        } else {
            $qtInit = '{}';
        }
        return $qtInit;
    }

    private function get_mce_init($editor_id) {
        if ( !empty(self::$mce_settings) ) {
            $options = self::_parse_init( self::$mce_settings );
            $mceInit .= "'$editor_id':{$options},";
            $mceInit = '{' . trim($mceInit, ',') . '}';
        } else {
            $mceInit = '{}';
        }
        return $mceInit;
    }

    private static function _parse_init($init) {
        $options = '';

        foreach ( $init as $k => $v ) {
            if ( is_bool($v) ) {
                $val = $v ? 'true' : 'false';
                $options .= $k . ':' . $val . ',';
                continue;
            } elseif ( !empty($v) && is_string($v) && ( ('{' == $v{0} && '}' == $v{strlen($v) - 1}) || ('[' == $v{0} && ']' == $v{strlen($v) - 1}) || preg_match('/^\(?function ?\(/', $v) ) ) {
                $options .= $k . ':' . $v . ',';
                continue;
            }
            $options .= $k . ':"' . $v . '",';
        }

        return '{' . trim( $options, ' ,' ) . '}';
    }

}


// the ajax respnose code
success : function(response){
    textarea.replaceWith(response);
    tinyMCE.init(tinyMCEPreInit.mceInit[data.id]);
    try { quicktags( tinyMCEPreInit.qtInit[data.id] ); } catch(e){}
}
3
Mike Allen