-
Notifications
You must be signed in to change notification settings - Fork 3
Toogle dropdown language switcher by click
Julien MA Jacob edited this page Aug 24, 2026
·
1 revision
This hook allows the opening and closing of the language switcher in dropdown mode to be triggered by clicks.
This hook injects both CSS and JavaScript into the <head> section of your website, allowing the dropdown to open when clicked and optionally close when clicking outside of it. The behavior is configurable through the $close_on_click_outside variable, which lets you decide whether the dropdown should close automatically when the user interacts outside the switcher.
/**
* Open and close the language switcher in dropdown mode by clicks
* Documentation: https://github.com/julien-jacob/wplingua/wiki/Toogle-dropdown-language-switcher-by-click/
*/
add_action( 'wp_head', 'wplingua_toogle_switcher_on_click', 20 );
function wplingua_toogle_switcher_on_click() {
// Set to true for close the language switcher on click outside
$close_on_click_outside = true;
$html = PHP_EOL;
/**
* CSS to control the dropdown behavior of the language switcher by click
*/
$html .= '<style id="wplng-style-open-switcher-on-click">';
// Collapse the dropdown when not explicitly opened
$html .= '.wplng-switcher.style-dropdown .switcher-content:hover .wplng-languages {';
$html .= ' height: 0;';
$html .= '}';
// Expand the dropdown when the custom class is added
$html .= '.wplng-switcher.style-dropdown .switcher-content.wplng-custom-open .wplng-languages {';
$html .= ' height: auto;';
$html .= '} ';
// End CSS
$html .= '</style>' . PHP_EOL;
/**
* JS to control the dropdown behavior of the language switcher by click
*/
$html .= '<script id="wplng-script-open-switcher-on-click">';
$html .= 'jQuery(document).ready(function ($) {';
if ( $close_on_click_outside ) {
// Attach a click event listener to the entire document
$html .= '$(document).on("click", function (event) {';
$html .= ' if (!$(event.target).closest(".wplng-switcher.style-dropdown .switcher-content").length) {';
$html .= ' $(".wplng-switcher.style-dropdown .switcher-content").removeClass("wplng-custom-open");';
$html .= ' }';
$html .= '});';
}
// Attach a click event listener to the language switcher
$html .= '$(".wplng-switcher.style-dropdown .switcher-content").on("click", function (event) {';
$html .= ' event.stopPropagation();';
$html .= ' $(this).toggleClass("wplng-custom-open");';
$html .= '});';
// End JS
$html .= '});';
$html .= '</script>' . PHP_EOL;
/**
* Clear and print
*/
// Remove all tabulations from the $html variable
$html = str_replace( "\t", '', $html );
echo $html;
}wpLingua · wordpress.org/plugins/wplingua · wpLingua.com · Terms & Conditions
Reference
Classic uses
Recipes