How to add wysiwyg editor in WordPress meta box

I’m creating a meta box for my custom post type. There are multiple fields where I would like to use wysiwyg editor rather than <textarea>. Is is possible to add multiple editors to a meta box?

I would really appreciate your help!

Read More

Many thanks.
Dasha

Related posts

Leave a Reply

8 comments

  1. Here is full code example:

    add_action( 'add_meta_boxes',  function() { 
        add_meta_box('html_myid_61_section', 'TITLEEEEE', 'my_output_function');
    });
    
    function my_output_function( $post ) {
        $text= get_post_meta($post, 'SMTH_METANAME' , true );
        wp_editor( htmlspecialchars($text), 'mettaabox_ID', $settings = array('textarea_name'=>'MyInputNAME') );
    }
    
    add_action( 'save_post', function($post_id) {
        if (!empty($_POST['MyInputNAME'])) {
            $datta=sanitize_text_field($_POST['MyInputNAME']);
            update_post_meta($post_id, 'SMTH_METANAME', $datta );
        }
    }); 
    

    P.S. MUST-Recommendation from my experience:

    Forget adding custom codes, use Advanced Custom Fields, it’s excellent and simplify your life.

  2. // for custom post type
    
    function wo_second_editor($post) {
    
      echo "<h3>Write here your text for the blue box on the right:</h3>";
      $content = get_post_meta($post->ID, 'wo_blue_box' , true ) ;
      wp_editor( htmlspecialchars_decode($content), 'wo_blue_box', array("media_buttons" => false) );
    }
    
    add_action('edit_form_advanced', 'wo_second_editor');
    
    
    function wo_save_postdata($post_id, $post, $update) {
    
      //...
    
      if (!empty($_POST['wo_blue_box'])) {
        $data=htmlspecialchars($_POST['wo_blue_box']);
        update_post_meta($post_id, 'wo_blue_box', $data );
      }
    }
    
    add_action('save_post', 'wo_save_postdata');
    
    
    // Theme:
    
    <div class="blue">
      <?php
      $content = get_post_meta(get_the_ID(), 'wo_blue_box' , true );
        $content = htmlspecialchars_decode($content);
        $content = wpautop( $content );
        echo $content;
      ?>
    </div>
    
  3. But you need to replace presentation with nl2br() function as textarea in custom templates have the toogle JS issue, that removes all your <P> and <br/> tags and therefore all line breaks.

  4. You can use the wordpress default text editor in the metabox using

    add_action( 'edit_page_form', 'my_second_editor' );
    function my_second_editor() {
        // get and set $content somehow...
        wp_editor( $content, 'mysecondeditor' );
    }
    
  5. First install TinyMCE Advanced plugin.
    Second add “theEditor” class to your textarea like this

    <textarea  class="theEditor" name="custom_meta_box"></textarea>
    

    Thats it
    😉

    Nabeel