Editor scrolling on save in WordPress
WordPress has a good editor, in my opinion, this editor has obvious inconveniences.
Every time, when you save a message, editor scroll position will be on top again. If you want to keep writing a long post, it will take you a lot of time, until you find the old cursor position.
To avoid this, I found a code snippet on the Internet, which I want to share with you.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
<?php /** * The class will help you to recover the old scoll position in your Editor. * Either HTML or visuel editor. */ final class Preserve_Editor_Scroll_Position { /** * Init */ public static function init() { add_filter( 'redirect_post_location', array( __CLASS__, 'add_query_arg' ) ); add_action( 'edit_form_advanced', array( __CLASS__, 'add_input_field' ) ); add_action( 'edit_page_form', array( __CLASS__, 'add_input_field' ) ); add_filter( 'tiny_mce_before_init', array( __CLASS__, 'extend_tiny_mce' ) ); } /** * Adds a hidden input field for scrolltop value */ public static function add_input_field() { $position = ! empty( $_GET['scrollto'] ) ? $_GET['scrollto'] : 0; printf( '<input type="hidden" id="scrollto" name="scrollto" value="%d"/>', esc_attr( $position ) ); // Print Javascript data add_action( 'admin_print_footer_scripts', array( __CLASS__, 'print_js' ), 55 ); // Print after Editor JS. } /** * Extend TinyMCE config with a setup function */ public static function extend_tiny_mce( $init ) { if ( 'tinymce' == wp_default_editor() ) $init['setup'] = 'rich_scroll'; return $init; } /** * Returns redirect url with query arg for scroll position */ public static function add_query_arg( $location ) { if ( ! empty( $_POST['scrollto'] ) ) $location = add_query_arg( 'scrollto', (int) $_POST['scrollto'], $location ); return $location; } /** * Prints Javascript data */ public static function print_js() { ?> <script> ( function( $ ) { $( '#post' ).submit( function() { scrollto = $( '#content' ).is( ':hidden' ) ? $( '#content_ifr' ).contents().find( 'body' ).scrollTop() : $( '#content' ).scrollTop(); $( '#scrollto' ).val( scrollto ); } ); $( '#content' ).scrollTop( $( '#scrollto' ).val() ); } )( jQuery ); function rich_scroll( ed ) { ed.onInit.add( function() { jQuery( '#content_ifr' ).contents().find( 'body' ).scrollTop( jQuery( '#scrollto' ).val() ); } ); }; </script> <?php } } add_action( 'plugins_loaded', array( 'Preserve_Editor_Scroll_Position', 'init' ) ); |
At the end, as always, some delicious. I suggest a plugin with a similar action Preserve Editor Scroll Position.