Comment Length Limiter

If you have used Twitter, then you know that you are only allowed to type 140 characters in a single Tweet. There is a nice little number below the text field indicating how much is left to write.

It would be nice to have this feature for WordPress comments too. Or any text field, for that matter. It can be done with the following piece of JavaScript:

jQuery(function($) {
        // configure
        var comment_input = $( '#commentform textarea' );
        var submit_button = $( '#commentform .form-submit' );
        var comment_limit_chars = 1000;
        // stop editing here
        // display how many characters are left
        $( '<div class="comment_limit_info"><span>' + comment_limit_chars + '</span> characters left</div>' ).insertAfter( comment_input );
        comment_input.bind( 'keyup', function() {
                // calculate characters left
                var comment_length = $(this).val().length;
                var chars_left = comment_limit_chars - comment_length;
                // display characters left
                $( '.comment_limit_info span' ).html( chars_left );
                // hide submit button if too many chars were used
                if (submit_button)
                        ( chars_left < 0 ) ? submit_button.hide() : submit_button.show();
        });
});

https://gist.github.com/1422754

The first three vars below the // configure comment can be edited.
comment_input is the DOM element of the text field.
submit_button is the DOM element for the button to submit the form.
Finally, comment_limit_chars is the amount of characters allowed.

This snippet automatically inserts a div tag below the text field and updates the character count when the user types. The submit_button is optional. Set the var to null if you don't want it to be grayed out.

Please keep in mind that this only validates the input on the client side. If you have to rely on the maximum text length, like Twitter does, you need to check the length on the back end side with PHP too.

Guest Post

This post is written by Eric Teubert - www.satoripress.com and is a post in our Advent Calendar on WP Engineer about WordPress.
Thank you very much from my part to Eric.
If you also like to have your interesting post published on our website, please let us know on our contact page. Of course we will appreciate your contribution!


WordPress Snippet PluginXtreme One WordPress Framework
© WP Engineer Team, All rights reserved (Digital Fingerprint: WPEngineer-be0254ce2b4972feb4b9cb72034a092d)

Advent Calendar – WordPress Editor: Preserve the scroll position

WordPress has a nice editor, with which are several hundreds of articles written daily.

But in my opinion the editor has an usability issue.
Every time you save a post the scroll position of the editor will be on top again. If you want to continue writing the post you have first to find he old position again. This can be time-consuming.

Save editor scroll position on saving

To avoid this behavior I have written a snippet which I want to share now with you.

<?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' ) );

If you want you can create your own plugin with this snippet or you can download the plugin Preserve Editor Scroll Position.

Guest Post

Dominik Schilling AvatarThis post is written by Dominik Schilling - wpgrafie.de and is a post in our Advent Calendar on WP Engineer about WordPress. Dominik is Student, Web Developer, WordPress Contributing Developer - ocean90 and he ♥ WordPress.
Thank you very much from my part to Dominik.
If you also like to have your interesting post published on our website, please let us know on our contact page. Of course we will appreciate your contribution!


WordPress Snippet PluginXtreme One WordPress Framework
© WP Engineer Team, All rights reserved (Digital Fingerprint: WPEngineer-be0254ce2b4972feb4b9cb72034a092d)

News Portal WordPress theme

News Portal WordPress theme

  • Bendable Control Panel (Theme Options Page), thаt allows tο set up theme settings frοm thе Administration Panel οf уουr WordPress
  • Adsense equipped. AƖƖ уου need іѕ tο include уουr Adsense-ID іn theme settings. Yου саn аƖѕο disable Adsense frοm administration panel іf уου don’t need іt.
  • Two different widgetized sidebars (fοr homepage аnԁ fοr аƖƖ οthеr pages).
  • Salutation text οn homepage саn bе easily set up аt theme administration panel.
  • 125×125 px Banner block. (Yου јυѕt need tο add banner HTML code аt theme administration panel)
  • Persona rotating Javascript look οn thе homepage. Yου саn add аnу pictures уου Ɩіkе (Picture size ѕhουƖԁ bе 510×190 px.). Pictures ѕhουƖԁ bе placed іntο a separate folder (/rotate_images)
  • Valid XHTML (verified bу w3.org)
  • Page navigation plugin built-іn (wp-pagenavi)

Localization with JavaScript in WordPress

Creating Plugins and Theme functions with multilanguage capability has been established knowadays.Especially for us as German developers it is a must have. But there are some difficulties if you are using JavaScript, the question is how to provide it multilingual or provide option values in different languages. WordPress offers some possibilities and I like to show them, since this question was asked by many and developers are searching for solutions. The following little example should show the realization and the easy output of strings demonstrates it. Wether strings for multilanguage or providing options values, it doesn't matter.

First we create a function with an array that contains the required content and can be accessed on the relevant content using variables.

function get_language_strings() {
    $strings = array(
        'example' => __( 'My Example String', TEXTDOMAIN_CONSTANT ),
        'foo'   => __( 'My foo string', TEXTDOMAIN_CONSTANT ),
        'bar'   => __( 'My bar', TEXTDOMAIN_CONSTANT )
    )
    return $strings;
}

When you call the extension, Plugin or Theme, the function must be loaded. For this task WordPress provides the function wp_localize_script() that takes care of everything:

wp_localize_script(
                       'my_foo',
                       'my_var_prefix',
                       $this->get_language_strings() // inside class
);

You can access the variables in the scripts:

alert( my_var_prefix.example );

No integration of wp-load.php or something like this, simply access the content. The strings are now translated into all languages using the classical methods and it applies only to create the appropriate files.


WordPress Snippet PluginXtreme One WordPress Framework
© WP Engineer Team, All rights reserved (Digital Fingerprint: WPEngineer-be0254ce2b4972feb4b9cb72034a092d)

Fix Empty Searches


One minor problem for any web site is duplicate content: the same resource is available under different URIs. Yes, we have <link rel=canonical>, but anything that prevents such cases is better.

Today, let’s look at something, that most professionals never see: empty searches. You offer a search input field, and someone hits the submit button unintentionally, without any term entered. The resulting URI looks like this: example.com/?s=. It shows the same content as your front page. In fact, it is the front page.

No one needs that.

Therefore, I have added a simple rule to my .htaccess:

# Catch empty searches
RewriteCond %{QUERY_STRING} ^s=$
RewriteRule ^ /? [L,R=301]

Add these lines right after the RewriteBase directive.

Next, I wanted to save my visitors the unnecessary request. I have written a simple jQuery plugin:

/**
 * Stop empty searches
 *
 * @author Thomas Scholz http://toscho.de
 * @param  $ jQuery object
 * @return bool|object
 */
(function( $ ) {
   $.fn.preventEmptySubmit = function( options ) {
       var settings = {
           inputselector: "#s",
           msg          : "Don’t waste your time with an empty search!"
       };
       if ( options ) {
           $.extend( settings, options );
       };
       this.submit( function() {
           var s = $( this ).find( settings.inputselector );
           if ( ! s.val() ) {
               alert( settings.msg );
               s.focus();
               return false;
           }
           return true;
       });
       return this;
   };
})( jQuery );

I call it in my footer scripts:

jQuery( "#searchform" ).preventEmptySubmit();

Note that my search form element has an id attribute with the value searchform. Adjust the selector to match your current theme. To change the message, just add an option for it:

jQuery( "#searchform" ).preventEmptySubmit({ msg: "This won’t work!" });

You may use the script for other input elements too. Set the selector in the second option inputselector. Say, you have a form with the id discountcode and a field with the id dcodenumber:

jQuery( "#discountcode" ).preventEmptySubmit(
{
   msg: "No number, no discount, sorry!",
   inputselector: "dcodenumber"
});

Useful? Any hints?

Guest Post

This post is written by Thomas Scholz - toscho.de and is a post in our Advent Calendar on WP Engineer about WordPress.
Thank you very much from my part to Thomas.
If you also like to have your interesting post published on our website, please let us know on our contact page. Of course we will appreciate your contribution!


WordPress Snippet PluginXtreme One WordPress Framework
© WP Engineer Team, All rights reserved (Digital Fingerprint: WPEngineer-be0254ce2b4972feb4b9cb72034a092d)




btbt
Designed by Wbcom Designs
#