diff --git a/config-templates/config.php b/config-templates/config.php
index 4ccf37c497bdd4e862c69a2867331bab6be55c4e..e5bc789bdbbadbc41475e55e989dc1d6bb5bbc9c 100644
--- a/config-templates/config.php
+++ b/config-templates/config.php
@@ -251,6 +251,18 @@ $config = array (
 	'language.rtl'		=> array('ar','dv','fa','ur','he'),
 	'language.default'		=> 'en',
 
+	/**
+	 * Custom getLanguage function called from SimpleSAML_XHTML_Template::getLanguage().
+	 * Function should return language code of one of the available languages or NULL.
+	 * See SimpleSAML_XHTML_Template::getLanguage() source code for more info.
+	 *
+	 * This option can be used to implement a custom function for determining
+	 * the default language for the user.
+	 *
+	 * Example:
+	 *   'language.get_language_function' => array('sspmod_example_Template', 'getLanguage'),
+	 */
+
 	/*
 	 * Extra dictionary for attribute names.
 	 * This can be used to define local attributes.
diff --git a/lib/SimpleSAML/XHTML/Template.php b/lib/SimpleSAML/XHTML/Template.php
index f5245596c358320c2bbfd4a79e23aa48fc42152d..e9da55d21d55b8f0f1706638ec348ec78f97c26f 100644
--- a/lib/SimpleSAML/XHTML/Template.php
+++ b/lib/SimpleSAML/XHTML/Template.php
@@ -97,6 +97,16 @@ class SimpleSAML_XHTML_Template {
 			return $this->language;
 		}
 
+		// Run custom getLanguage function if defined
+		$customFunction = $this->configuration->getArray('language.get_language_function', NULL);
+		if (isset($customFunction)) {
+			assert('is_callable($customFunction)');
+			$customLanguage = call_user_func($customFunction, $this);
+			if ($customLanguage !== NULL && $customLanguage !== FALSE) {
+				return $customLanguage;
+			}
+		}
+
 		// Language is provided in a stored COOKIE
 		$languageCookie = SimpleSAML_XHTML_Template::getLanguageCookie();
 		if ($languageCookie !== NULL && in_array($languageCookie, $this->availableLanguages, TRUE)) {