Skip to content

Instantly share code, notes, and snippets.

@sh-sabbir
Last active March 18, 2019 16:24
Show Gist options
  • Save sh-sabbir/a14b7638cca73fd35da92163176f4fab to your computer and use it in GitHub Desktop.
Save sh-sabbir/a14b7638cca73fd35da92163176f4fab to your computer and use it in GitHub Desktop.
//Modify this function only
function countries() {
$args = array(
'post_type' => 'country', //change as needed
'post_status' => 'publish',
'posts_per_page' => -1);
$slugs = array();
$countries = new WP_Query( $args );
if ( $countries->have_posts() ) :
while ( $countries->have_posts() ) : $countries->the_post();
array_push( $slugs, get_post_field( 'post_name', get_the_ID()) );
endwhile;
endif;
return $slugs;
}
function prepend_default_rewrite_rules( $rules ) {
// Prepare for new rules
$new_rules = [];
// Set up Country, except default one
//$country_slugs = ['us', 'bd', 'in', 'uk', 'cn'];
$country_slugs = countries();
// Generate language slug regex
$countries_slug = '(?:' . implode( '/|', $country_slugs ) . '/)?';
// Set up the list of rules that don't need to be prefixed
$whitelist = [
'^wp-json/?$',
'^wp-json/(.*)?',
'^index.php/wp-json/?$',
'^index.php/wp-json/(.*)?'
];
// Set up the new rule for home page
$new_rules['(?:' . implode( '/|', $country_slugs ) . ')/?$'] = 'index.php';
// Loop through old rules and modify them
foreach ( $rules as $key => $rule ) {
// Re-add those whitelisted rules without modification
if ( in_array( $key, $whitelist ) ) {
$new_rules[ $key ] = $rule;
// Update rules starting with ^ symbol
} elseif ( substr( $key, 0, 1 ) === '^' ) {
$new_rules[ $countries_slug . substr( $key, 1 ) ] = $rule;
// Update other rules
} else {
$new_rules[ $countries_slug . $key ] = $rule;
}
}
// Return out new rules
return $new_rules;
}
add_filter( 'rewrite_rules_array', 'prepend_default_rewrite_rules' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment