I solved this issue by comparing the locale with the url prefix.
So if the locale is nl_NL, I split up the string by the ‘_’ character and take the ‘nl’ part. Now I take the post url: https://www.blog.com/nl/post-id. Split the string with ‘//’, take the first element of the array. Then split with with ‘/’. And take the first element of that array. What you will get is ‘nl’ for all Dutch pages.
With this information you can compare the page language to the locale language and decide whether to display a post or not. I achieved this with the following code.
Apologies because it’s not generic. You might need to adapt a few things in order for you to get it to work.
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav navbar-right">
<?php
$menu_args = array(
'sort_order' => 'DESC',
'sort_column' => 'menu_order',
'hierarchical' => 1,
'exclude' => '',
'include' => '',
'meta_key' => '',
'meta_value' => '',
'authors' => '',
'child_of' => 0,
'parent' => -1,
'exclude_tree' => '',
'number' => '',
'offset' => 0,
'post_type' => 'page',
'post_status' => 'publish'
);
$mypages = get_pages($menu_args);
$locale = get_locale();
$localeexpl = explode("_", $locale);
$locallang = $localeexpl[0];
//echo "Locale: ".$locallang."<br>";
$i_incl_posts = 0;
foreach( $mypages as $page ) {
$perm = get_page_link( $page->ID );
$permexplode = explode("//", $perm);
$urlwithouthttp = $permexplode[1]; // $string without https://
//echo $urlwithouthttp."<br>";
$chunks = explode("/", $urlwithouthttp);
$url_language = $chunks[1];
//echo "1".$url_language."<br>";
if ($url_language != 'nl' && $url_language != 'de') {
$url_language = 'en';
}
if ($url_language == $locallang){
$includedpages[$i_incl_posts] = $page->ID;
$i_incl_posts++;
}
};
$displaypages = implode(",", $includedpages);
//echo $displaypages;
?>
<div>
<ul class="menu">
<?php $args = array(
'authors' => '',
'child_of' => 0,
'date_format' => get_option('date_format'),
'depth' => 0,
'echo' => 1,
'exclude' => '',
'include' => $displaypages,
'link_after' => '',
'link_before' => '',
'post_type' => 'page',
'post_status' => 'publish',
'show_date' => '',
'sort_column' => 'menu_order, post_title',
'title_li' => '',
'walker' => ''
); ?>
<?php wp_list_pages($args); ?>
</ul>
</div>
<?php $locale = get_locale();
if ('en_US' == $locale ) { ?>
<?php $language = "Language"; ?>
<?php } elseif ('nl_NL' == $locale ) { ?>
<?php $language = "Taal"; ?>
<?php } elseif ('de_DE' == $locale ) { ?>
<?php $language = "Sprache"; ?>
<?php } else { ?>
<?php $language = "Language"; ?>
<?php } ?>
<div>
<ul class="menu">
<li><a><?php echo $language; ?></a>
<ul class="sub-menu">
<?php echo do_shortcode( '[bogo]' ); ?>
</ul>
</li>
</ul>
</div>
<script>
//If li has hyperlink, no padding, if no hyperlink, old padding
$( "#menu ul.language-switcher > li:has(a)" ).addClass( "nopadding" );
</script>
</ul>
</div><!--/.nav-collapse -->