I’ve defined a custom post type, projects
, and I’ve set the permalink for those post types to /projects/my-project/
.
However, for one of the projects, I need to give it a special URL, so instead of /projects/special-project/
it appears on /special-project/
.
Is that possible?
1 Answer
Try adding the following to your functions.php
:
function wpse221475_custom_rewrite_rules() {
add_rewrite_rule(
'^(special-project)?',
'index.php?post_type=projects&name=$matches[1]',
'top'
);
}
add_action('init', 'wpse221475_custom_rewrite_rules');
Make sure to flush your rewrite rules after adding this rule.
Visit:
Dashboard -> Settings -> Permalinks
Or if you wish, you can use flush_rewrite_rules()
programmatically.
To redirect requests for http://example.com/projects/special-project
to http://example.com/special-project
you can parse the request on the wp
hook.
function wpse221475_redirect_request($wp) {
if ( ! empty($wp->request) && $wp->request === 'projects/special-project' ) {
wp_redirect(home_url('special-project'), 301);
exit;
}
}
add_action('wp', 'wpse221475_redirect_request');
Of course there are other ways/methodologies you could use to achieve the same effect but the above will suffice.