I have a scenario in which the intention is to make custom permalink that can be changed dynamically, for example:
If a country information is showing up then the URL should be
If the city information of that specific country is showing up then the URL should be like .
How can I achieve that?
I have a scenario in which the intention is to make custom permalink that can be changed dynamically, for example:
If a country information is showing up then the URL should be http://example.com/country-information
If the city information of that specific country is showing up then the URL should be like http://example.com/country/city-information
.
How can I achieve that?
It depends on what you mean by "changed dynamically", but the simplest way to achieve what you're talking about is to use pages (or a hierarchical custom post type), and make the "city-information" pages into children of the "country-information" page they are associated with. Then set permalinks to "Post Name", and you'll get the urls you're looking for.
Did you try add_rewrite_rule()
? For example:
add_action( 'init', function() {
add_rewrite_rule( 'country-information/([a-z0-9-]+)[/]?$', 'index.php?country-information=$matches[1]', 'top' );
} );
After adding the new rule, you have to flush the permalink, Admin > Permalinks > Save
Then add a new query var via add_filter
, needed to allow custom rewrite rules using your own arguments to work, or any other custom query variables you want to be publicly available.
add_filter( 'query_vars', function( $query_vars ) {
$query_vars[] = 'country-information';
return $query_vars;
} );
You can also use a custom particular template for that permalink using template_include
hook.
function conutry_information_template( $template ) {
if ( get_query_var( 'country-information' ) === false || get_query_var( 'country-information' ) == '' ) {
return $template;
}
return get_template_directory() . '/country-information.php';
}
add_action( 'template_include', 'conutry_information_template' );