2

I noticed that my edit post WP editor expands automatically when writing. However my WP editor instances I use for my other Custom post types don't.

I investigated a bit I and I see that the iframe including the textarea in the built-in edit post has a body which has a "wp-autoresize" class. The ones of my custom posts don't. I thought that adding that class would be all I need to allow the autoresize feature. At least, it was worth the try.

So, I try to add this class to the iframe bodies of my CPT plugins like this:

add_filter( 'tiny_mce_before_init', 'wpse_235194_tiny_mce_classes' );
function wpse_235194_tiny_mce_classes( $init_array ){
  global $post;
    $init_array['body_class'] .= ' ' . join( ' ', 'wp-autoresize' );
  return $init_array;
}

But the class doesn't appear there.

I tried this too (willing then to target each CP iframe id specifically):

$("iframe#_xxx_textarea").contents().find("body").addClass("wp-autoresize");

No success neither.

Whatever I tried to add a class to an iframe body was just a failure.

So I tried to just bypass this body class approach to add the auto-resize feature for TinyCME in another way:

function init_tinymce_autoresize($initArray){
   $initArray['plugins'] = "autoresize";
   return $initArray;
}
add_filter('tiny_mce_before_init', 'init_tinymce_autoresize');

Nope.

And then tried to add a more sophisticated handmade plugin as described here:

TinyMCE Autoresize

But nothing happens neither.

And by nothing, I mean that when my text grows big as I type, the textarea keeps its original height and I have to scroll to see the whole content.

Some I'm stuck as I believe I tried all the standard solutions I found in the previous 3 hours. Now I keep finding the same solutions I tried already.

So how can I achieve an autoresize on custom TinyMCE editors applied to Custom posts?

Thanks.

EDIT: I've been asked to show the way I registered the CPT:

    function xxx_custom_type_init()
    {
        register_post_type('xxx', array(
          'labels' => array(
          'name' => 'xxx',
          'singular_label' => 'xxx',
          'add_new' => 'Ajouter',
          'add_new_item' => 'Ajouter un élément',
          'new_item' => 'Nouvel élément',
          'view_item' => 'Afficher l\'élément',
          'edit_item' => 'xxx',
          'not_found' => 'Auncun élément trouvé',
          'not_found_in_trash' => 'Auncun élément dans la corbeille'),
          'public' => true,
          'show_ui' => true,
          'capability_type' => 'post',
          'hierarchical' => false,
          'supports' => array('')
        ));
        register_taxonomy_for_object_type( 'category', 'xxx' );
    }
    add_action('init', 'xxx_custom_type_init');

    function xxx_custom_type_messages( $messages ) 
    {
        global $post, $post_ID;
        $messages['xxx'] = array(
            1 => sprintf(__('xxx updated. <a href="%s">See xxx</a>','your_text_domain'),esc_url(get_permalink($post_ID))),
            4 => __('xxx updated.', 'your_text_domain'),
            6 => sprintf(__('xxx published. <a href="%s">See xxx</a>','your_text_domain'),esc_url(get_permalink($post_ID))),
            7 => __('xxx saved.','your_text_domain'),
            9 => sprintf(__('Elément prévu pour: <strong>%1$s</strong>. <a target="_blank" href="%2$s">Prévisualiser l\'élément</a>','your_text_domain'),
            date_i18n(__('M j, Y @ G:i'),strtotime($post->post_date)),esc_url(get_permalink($post_ID))),
            10 => sprintf(__('Brouillon mis à jour. <a target="_blank" href="%s">Prévisualiser l\'élément</a>','your_text_domain'),esc_url(add_query_arg('preview','true',get_permalink($post_ID)))),
        );
        return $messages;
    }
    add_filter( 'post_updated_messages', 'xxx_custom_type_messages' );

And here how I added an editor to my CP admin page:

<?php

add_action( 'add_meta_boxes', 'xxx_textarea_add_fields_metabox');
function xxx_textarea_add_fields_metabox() 
{
    add_meta_box(
        'xxx_textarea_metabox', 
        'Intro', 
        'xxx_textarea_show_fields_metabox', 
        'xxx', 
        'side', 
        'default'
    );
}

function xxx_textarea_show_fields_metabox()
{   
    global $post; 
    $content = get_post_meta($post->ID, '_xxx_textarea', true); 

    ?>  

    <style> 

        iframe#_xxx_textarea_ifr
            {width:100%;height:auto !important;display:block;}
        iframe#_xxx_textarea_ifr html
            {overflow:hidden;display: block;}
        iframe#_xxx_textarea_ifr body
            {overflow:hidden;display: block;}
        #_xxx_textarea
            {height:auto;overflow-y: hidden;min-height: 35px;overflow-x: hidden;overflow-y: auto;}

    </style>    

    <?php   

    $args = array(
        'description_name' => '_xxx_textarea',
         'teeny' => true,
         'quicktags' => false,
         'media_buttons' => false,
         'tinymce' => array(
             'toolbar1'=> 'bold,italic,underline,link,unlink,forecolor',
             'toolbar2' => '',
             'toolbar3' => ''
         )
    );
    wp_editor( $content, '_xxx_textarea', $args );
    wp_nonce_field(plugin_basename(__FILE__), 'xxx_textarea_noncename');    
};      

add_action('save_post', 'xxx_textarea_save_fields_metabox', 1, 2);
function xxx_textarea_save_fields_metabox($post_id, $post) 
{
    global $post_id;

    if ( !wp_verify_nonce( $_POST['xxx_textarea_noncename'], plugin_basename(__FILE__) )){return $post->ID;}  
    if ( !current_user_can( 'edit_post', $post->ID ))                                      {return $post->ID;}   
    if( $post->post_type == 'revision' )                                                 {return;$post->ID;}

    if($_POST['_xxx_textarea']) {$xxx_content = $_POST['_xxx_textarea'];}
    else{$xxx_content = '';};

    if(get_post_meta($post_id, '_xxx_textarea', FALSE)){update_post_meta($post_id, '_xxx_textarea', $xxx_content);} 
    else{ add_post_meta($post_id, '_xxx_textarea', $xxx_content);};             
}

I hope it helps.

Just FYI, I styled the iframe and body of my CPT exactly the same than the ones I found for the standard edit post.

I added the "!important" flag to the height of the iframe because it seems that, somewhere in a WP file, it's set to 400px. So, this way, it's clearly overridden.

So, I should not expect anything blocking on the CSS part but I can't be absolutely positive about this.

3
  • 1
    Not sure, how you registered your CPT, I tried registering one with the CPT UI plugin and it seems to be working fine. "wp-autoresize" gets added by default. Maybe you want to confirm it by registering another CPT.
    – Kumar
    Commented Oct 27, 2017 at 6:57
  • Tomorrow I will update my question to show you how I registered my CPT. Thanks for your help and concern. Commented Oct 28, 2017 at 3:48
  • I don't use an external plugin, I just register my CPT's the way I always do (see the edited initial post). I also added the way I add the texarea/editor on my CP admin edit page. Thanks for your help. Commented Oct 28, 2017 at 13:12

2 Answers 2

4

Finally I got around this.

You need to modify tinymce args passed to wp_editor function. WordPress have a argument wp_autoresize_on to allow the editor to be resized automatically.

So instead of these:

'tinymce' => array(
         'toolbar1'=> 'bold,italic,underline,link,unlink,forecolor',
         'toolbar2' => '',
         'toolbar3' => ''
     )

you need to use this:

'tinymce' => array(
        'autoresize_min_height' => 100,
        'wp_autoresize_on'      => true,
        'plugins'               => 'wpautoresize',
        'toolbar1'              => 'bold,italic,underline,link,unlink,forecolor',
        'toolbar2'              => '',
    ),

There are two additional args in here, autoresize_min_height, you can set it to desired height, and second one is 'wp_autoresize_on' => true,. Apart from that you need to pass additional parameter to load the tinymce plugin for auto resizing and i.e 'plugins' => 'wpautoresize' and the auto resizing works flawlessly.

With these changes, I'd suggest you add some other checks in your code. Like for the function:

function xxx_textarea_save_fields_metabox($post_id, $post) {
  global $post_id;

  if ( !wp_verify_nonce( $_POST['xxx_textarea_noncename'], plugin_basename(__FILE__) )){return $post->ID;}  
  if ( !current_user_can( 'edit_post', $post->ID ))                                      {return $post->ID;}   
  if( $post->post_type == 'revision' )                                                 {return;$post->ID;}

  if($_POST['_xxx_textarea']) {$xxx_content = $_POST['_xxx_textarea'];}
  else{$xxx_content = '';};

  if(get_post_meta($post_id, '_xxx_textarea', FALSE))
  {update_post_meta($post_id, '_xxx_textarea', $xxx_content);} 
  else{ add_post_meta($post_id, '_xxx_textarea', $xxx_content);};             

  }

Make sure to add a check for empty $_POST, otherwise you'll get notices on post edit screen. I've made the changes and formatted the code ( You should be doing that ), here is the whole code for adding metabox.

add_action( 'add_meta_boxes', 'xxx_textarea_add_fields_metabox' );
function xxx_textarea_add_fields_metabox() {
    add_meta_box(
        'xxx_textarea_metabox',
        'Intro',
        'xxx_textarea_show_fields_metabox',
        'new_xxx',
        'side',
        'default'
    );
}

function xxx_textarea_show_fields_metabox() {
    global $post;
    $content = get_post_meta( $post->ID, '_xxx_textarea', true );
    //Loads the editor to allow adding fresh content if there is no content already
    $content = empty( $content ) ? '' : $content;

    $args = array(
        'description_name' => 'xxx_textarea',
        'teeny'            => true,
        'quicktags'        => false,
        'media_buttons'    => false,
        'tinymce'          => array(
            'autoresize_min_height' => 100,
            'wp_autoresize_on'      => true,
            'plugins'               => 'wpautoresize',
            'toolbar1'              => 'bold,italic,underline,link,unlink,forecolor',
            'toolbar2'              => '',
        ),
    );
    wp_editor( $content, '_xxx_textarea', $args );
    wp_nonce_field( plugin_basename( __FILE__ ), 'xxx_textarea_noncename' );
}

add_action( 'save_post', 'xxx_textarea_save_fields_metabox', 1, 2 );
function xxx_textarea_save_fields_metabox( $post_id, $post ) {
    global $post_id;

    //Avoids notice and warnings
    if( empty( $_POST ) ) {
        return $post->ID;
    }
    if ( !empty( $_POST['xxx_textarea_noncename'] ) && ! wp_verify_nonce( $_POST['xxx_textarea_noncename'], plugin_basename( __FILE__ ) ) ) {
        return $post->ID;
    }
    if ( ! current_user_can( 'edit_post', $post->ID ) ) {
        return $post->ID;
    }
    if ( $post->post_type == 'revision' ) {
        return;
        $post->ID;
    }

    if ( $_POST['_xxx_textarea'] ) {
        $xxx_content = $_POST['_xxx_textarea'];
    } else {
        $xxx_content = '';
    };

    if ( get_post_meta( $post_id, '_xxx_textarea', false ) ) {
        update_post_meta( $post_id, '_xxx_textarea', $xxx_content );
    } else {
        add_post_meta( $post_id, '_xxx_textarea', $xxx_content );
    };
}

That should do it. Corresponding Post: http://codechutney.com/auto-resize-wp-editor-custom-instance/

6
  • Thank you very much. I'll try this all tomorrow and will get back to you. Thanks! Commented Nov 1, 2017 at 10:15
  • I am not leaving this halfway at all Sven. It's just that I couldn't test it yet because I had to take care of the security first for hacking reasons (someone broke into my admin even though I have the latest version of WP). But I can just say it's the right answer if you are confident it will work. I respect and value your help very much and will not leave it without a proper feedback and acceptance. Just that some server issues got in the way. Anyway, I just accepted the answer and will still get back to you whether it works or not. Thank you very much. Commented Nov 7, 2017 at 5:35
  • 1
    Ahh ok! "I had to take care of the security first for hacking reasons" Did you figure out what and how? Sorry if I was being rude, it's just I put in quite some time figuring this out and seeing it all go in vain I commented.
    – Kumar
    Commented Nov 7, 2017 at 6:07
  • 1
    Ok, finally I got the site to work again and, YES, your trick worked, thank you very much! It has a side effect (of course) as it just made my link/unlink buttons disappear but that's another story... Commented Nov 13, 2017 at 14:07
  • 2
    Just FYI: in order to have it working while keeping all my buttons active, I have to change 'plugins' to 'plugin'. Don't know why as the autoresize works in both cases but with the word in plural, some buttons are missing. Commented Nov 14, 2017 at 7:34
0

I realise this is several years later and I don't know if this functionality was available at the time but now its as easy as passing wp_autoresize_on as true to the setup config

In javascript

wp.editor.initialize('case-'+caseid+'-post_content', {'tinymce': {
                    'wp_autoresize_on' : true
                }, 'quicktags': true, 'mediaButtons': true});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.