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.
Continue reading …

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 );
               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!

Category And Archive Dropdown With Unobtrusive JavaScript

A good website works when a user comes along with JavaScript disabled, just as well as with scripting enabled. You separate the JS layer of the site from anything else (and waived for example, onclick in HTML) and places the scripts in a way that only improves the already existing functionality of the site. So the visitors can navigate through the website with and without JS, even though it might be a little more difficult or less attractive without scripting. This approach to scripting on sites is called Unobtrusive JavaScript. Jenn Lukas gives in this talk at the JSConf 2010 reasons why it's a good thing. Besides all the good reasons, the main argument for unobtrusive JavaScript that is to be implemented with appropriate planning so easily that it would be a wasted potential if you would without it. The problem can be alone if the used CMS makes problem - which brings us to WordPress.

Occasionally you like to have in your blog sidebar drop down menus (select-elements) to navigate the categories and the archive and the WordPress Codex provides the documentation and appropriate solutions for archive in which, however, both with only activated JavaScript function. In both cases, the URL of the destination page is stored in the value-value of the built-in option elements of the drop-down menu and when you select an entry, you will be forwarded via JavaScript on the very URL. The almost same functionality could be achieved also without scripts:

  1. Create an old-fashioned GET form with submit button that sends to the base address of the site
  2. Put the select in this very form and specify name="cat"
  3. Give the option elements the slug of the categories

Submitting the form will result in a call to blog.de/?cat=category and thus the desired category, possibly with a redirect to the search engine friendly version of the URL. This works for the visitors just as good as the solution of the Codex, leaving aside the fact that you have to click on a button. But this is where you can engage with JavaScript to hide the button and sending the form via, by a script inserted, onclick handle . The end result looks like the script for users with Codex solution and all others come then just by clicking on the button to its destination and everyone is happy. So let's get to work!

The basis for the category drop forms creates a normal HTML form:

<form id="kategorienform" action="<?php bloginfo('url'); ?>" method="get">
    <label for="kategorienselect">Jump to Category</label>
    <select id="kategorienselect" name="cat">
        <option value="">-- Please Select</option>
            $categories = get_categories('hierarchical=0');
            foreach($categories as $category){
                $selected = (is_category($category->cat_ID)) ? 'selected' : '';
                echo '<option '.$selected.' value="'.$category->cat_ID.'">'.$category->cat_name.' ('.$category->count.')</option>';
    <input id="kategorienbutton" value="Kategorie abrufen" type="submit">

You could use this in your side bar and it would work, but we still want to get rid of the submit button and start forwarding directly when selecting a category. For this purpose, it does not take more than 6 lines of JavaScript that can be inserted directly below the form:

<script type="text/javascript">
    document.getElementById('kategorienselect').onchange = function(){
    document.getElementById('kategorienbutton').style.display = 'none';

If the user changes his selection in select element, is (if not the entry "Please select" is selected) submitting the form automatically, without having to activate the with style.display = 'none' made invisible button - done is the most user-friendly and still working without JavaScript category dropdown! This is a bit more code than the three lines from the Codex, but it works guaranteed on every visitor. And the principle is quite simple, provided you plan accordingly in advance. Since this is not happening in WordPress not even happen, we need to tap a little more - or in the case of the archive dropdown even much more:

<form id="archivform" action="<?php bloginfo('url'); ?>" method="get">
    <label for="archivselect">skip to month</label>
    <select id="archivselect" name="m">
        <option value="">-- Please select</option>
            $query = "SELECT YEAR(post_date) AS `year`, MONTH(post_date) AS `month`, COUNT(ID) as `posts`
                FROM $wpdb->posts
                WHERE post_type = 'post' AND post_status = 'publish'
                GROUP BY YEAR(post_date), MONTH(post_date)
                ORDER BY post_date DESC";
            $key = md5($query);
            $cache = wp_cache_get('select_archives', 'general');
                $arcresults = $wpdb->get_results($query);
                $cache[$key] = $arcresults;
                wp_cache_set('select_archives', $cache, 'general');
                $arcresults = $cache[$key];
                global $wp_locale;
                foreach((array) $arcresults as $arcresult){
                    $value = $arcresult->year.$arcresult->month;
                    $text = sprintf(__('%1$s %2$d'), $wp_locale->get_month($arcresult->month), $arcresult->year);
                    $count = ' ('.$arcresult->posts.')';
                    $selected = (is_month() && get_query_var('year').get_query_var('monthnum') == $value) ? 'selected' : '';
                    echo '<option '.$selected.' value="'.$value.'">'.$text.$count.'</option>';
    <input id="archivbutton" value="Archiv abrufen" type="submit">

The problem with the Archive, is that without a custom SQL query, you cannot get to the information, which you need for a monthly archive. So there is no other way then to manually enter the database and cache the result manually. The principle is identical: simply output a conventional form and then six small lines of JavaScript:

<script type="text/javascript">
    document.getElementById('archivselect').onchange = function(){
    document.getElementById('archivbutton').style.display = 'none';

To summarize: many lines of code, but the principle is not complicated. Unobtrusive JavaScript is a question of intelligent planning and if it is not included as with WordPress automatically, you have to do it. With traditional websites, there is no reason to operate completely dependent on JavaScript, and should there be more effort, it is worth the clean separation of the layers and the accessibility bonus.

Guest Post

This post was written by Peter Kröner peterkroener.de.

Peter Kröner is freelance web designer and developer and also author of the HTML5-book.
On peterkroener.de he blogs on all kind of topics in web technology.

Thank you very much from our part to Peter.

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!

Use JavaScript Libraries In And Of WordPress

If you develop in and for WordPress, it's advisable to use a library of the core and a Plugin for the the library with the desired effect.

Same for theme and Plugin authors. If you use a function of WordPress to implement JavaScript, you will have less complications and the compatibility between Plugins is much higher.
I will show you an example with Thickbox how to use JavaScript from the core.

There are many possibilities to implement the „Lightbox“ effect on your website. Let's take a close look on a way to use it without a Plugin.
WordPress has Thickbox in their standard installation, so it's not very complicated to use it.
Continue reading …