I am trying to load the CodeMirror editor to be used in a plugin backend. Some textareas are for HTML and some are for CSS. I am quite new to WP development, so pardon my ignorance, but doing this:

    add_action('admin_enqueue_scripts', 'joermo_enqueue_scripts');
    function joermo_enqueue_scripts($hook) {
        $joermo_html_code['ce_html'] = wp_enqueue_code_editor(array('type' => 'text/html'));
        $joermo_css_code['ce_css'] = wp_enqueue_code_editor(array('type' => 'text/css'));
        wp_localize_script('jquery', 'joermo_html_code', $joermo_html_code);
        wp_localize_script('jquery', 'joermo_css_code', $joermo_css_code);

        wp_enqueue_script('wp-theme-plugin-editor');
        wp_enqueue_style('wp-codemirror');
    }

I only get the one that is last declared, here CSS. How can I get both?

This is my js:

jQuery( function() {
    wp.ce_html.initialize(jQuery('.joermo-html-code-editor'), joermo_html_code);
} );

And HTML:

<textarea class="joermo-html-code-editor" name="shipping_label_text">' . $shipping_label_text . '</textarea>

And also, is it not possible to .initzialie() several textareas with a shared class in one go? Do I have to call each one by id?

4 Answers
4

I just ran into this exact issue and with a tiny bit of tweaking it should work, what you have is 90% of the way there.

I’ve tweaked your code slightly so it should now work.

The PHP:

add_action('admin_enqueue_scripts', 'joermo_enqueue_scripts');
function joermo_enqueue_scripts($hook) {
    $joermo_code['ce_html'] = wp_enqueue_code_editor(array('type' => 'text/html'));
    $joermo_code['ce_css'] = wp_enqueue_code_editor(array('type' => 'text/css'));
    wp_localize_script('jquery', 'joermo_code', $joermo_code);

    wp_enqueue_script('wp-theme-plugin-editor');
    wp_enqueue_style('wp-codemirror');
}

The jQuery:

jQuery(function() {
    wp.ce_html.initialize(jQuery('.joermo-html-code-editor'), joermo_code);
    wp.ce_css.initialize(jQuery('.joermo-css-code-editor'), joermo_code);
});

Before I got the above working, I tried exactly the same as you did with running wp_localize_script twice. But $joermo_html_code['ce_html'] & $joermo_css_code['ce_css'] can be switched to an array and then you only need to run localize once. So in my example it became $joermo_code['ce_html'] & $joermo_code['ce_css'].

Hope this helps!

Leave a Reply

Your email address will not be published. Required fields are marked *