Below are the revised callbacks for pre_get_posts and post_link with fallback code in place. Replace what you currently have with these versions. In the tg_add_region() callback, I’ve assumed the IDs for the Benelux-News and International-News categories are 123 and 124 respectively. You must use the actual IDs in each line (that begins with if ( in_array(...
) so that the proper location term can be assigned.
// Insert region into post links
add_filter('post_link', 'tg_add_region', 999, 3 );
function tg_add_region( $link, $post, $leavename) {
global $region;
$cats = wp_get_post_categories( $post->ID, array('fields'=>'ids',));
if ( in_array( 123, $cats )) $region = 'benelux';
if ( in_array( 124, $cats )) $region = 'international';
if ( null == $region ) $region = 'international';
$link = str_replace('.com/', ".com/$region/", $link );
return $link;
}
// Add region category to main queries
add_action('pre_get_posts', 'tg_set_region');
function tg_set_region( $query ) {
if ( get_option('page_on_front') == $query->get('page_id')) return;
if ( !is_admin() && $query->is_main_query()) {
global $region;
$explode = explode('/', $_SERVER['REQUEST_URI']);
$cat = $query->get('category_name');
$region = $explode[1];
if ( ! in_array( $region, array('benelux','international',))) $region = 'international';
if ( '' != $cat ) $cat .= '+' . $region;
else $cat = $region;
$query->set('category_name', $cat);
}
}
When inserting the region in post links, we try to use the assigned category to decide upon the region. In both the post_link and pre_get_posts callbacks, when all else fails in assigning the correct region, we use “international”.