Recently I needed a function that will return only language-switching urls. When people are using many languages and pages and they want to create their own language switcher, the possibilities provided in
function the_languages($args = '')
or simply
pll_the_languages($args )
are not enough unless function is modified.
I modify it, so it will return the array of urls corresponding to each language. Here is the code:
// displays (or returns) the language switcher
function the_languages($args = '') {
$defaults = array(
'only_urls' => 0,
'dropdown' => 0, // display as list and not as dropdown
'echo' => 1, // echoes the list
'hide_if_empty' => 1, // hides languages with no posts (or pages)
'menu' => '0', // not for nav menu
'show_flags' => 0, // don't show flags
'show_names' => 1, // show language names
'display_names_as' => 'name', // valid options are slug and name
'force_home' => 0, // tries to find a translation (available only if display != dropdown)
'hide_if_no_translation' => 0, // don't hide the link if there is no translation
'hide_current' => 0, // don't hide current language
);
extract(wp_parse_args($args, $defaults));
if ($only_urls)
{
$echo = 0;
$show_flags = 0;
$show_names = 0;
$dropdown = 0;
$urls = array();
}
if ($dropdown)
$output = $this->dropdown_languages(array('hide_empty' => $hide_if_empty, 'selected' => $this->curlang->slug));
else {
$output = '';
foreach ($this->get_languages_list($hide_if_empty) as $language) {
// hide current language
if ($this->curlang->term_id == $language->term_id && $hide_current)
continue;
$url = $force_home ? null : $this->get_translation_url($language);
$url = apply_filters('pll_the_language_link', $url, $language->slug, $language->description);
// hide if no translation exists
if (!isset($url) && $hide_if_no_translation)
continue;
$url = isset($url) ? $url : $this->get_home_url($language); // if the page is not translated, link to the home page
$class = 'lang-item lang-item-'.esc_attr($language->term_id);
$class .= $language->term_id == $this->curlang->term_id ? ' current-lang' : '';
$class .= $menu ? ' menu-item' : '';
$flag = $show_flags ? $this->get_flag($language) : '';
$name = $show_names || !$show_flags ? esc_html($display_names_as == 'slug' ? $language->slug : $language->name) : '';
$output .= sprintf("<li class='%s'><a hreflang='%s' href='%s'>%s</a></li>\n",
$class, esc_attr($language->slug), esc_url($url), $show_flags && $show_names ? $flag.' '.$name : $flag.$name);
$urls[esc_attr($language->slug)] = esc_url($url);
}
}
if ($only_urls)
{
return $urls;
}
$output = apply_filters('pll_the_languages', $output, $args);
if(!$echo)
return $output;
echo $output;
}
I just added one more argument: only_urls, which ignores all other arguments and an array containing language urls is returned.
Example:
Array ( [en] => http://localhost/wordpress/about-us/ [sk] => http://localhost/wordpress/o-nas/ )
I find it useful, so I shared.