I would go with a custom function hooked to template_redirect
action, because
This action hook executes just before WordPress determines which
template page to load. It is a good hook to use if you need to do a
redirect with full knowledge of the content that has been queried.
Source: https://developer.wordpress.org/reference/hooks/template_redirect/
In the custom function you can first check, if the current query has the result of "not found" with an if
statement against is_404()
. If not, return early, otherwise keep going. Then dig in to the global variable $wp
to get the requested path.
Use the path with get_term_by()
to look for a category with the same slug. If found, get_term_link()
, and wp_redirect()
to it without forgetting to exit;
. Otherwise let WP keep doing what it was doing and display the 404 page for the original query.
For example like this,
add_action('template_redirect', function(){
// do nothing, if not a 404
if ( ! is_404() ) {
// return
}
// WordPress environment setup class
// https://developer.wordpress.org/reference/classes/wp/
global $wp;
// try to find term with slug
$maybeCategory = get_term_by(
'slug',
basename($wp->request), // the last part of the requested path
'category'
);
// redirect to category, if it exists
if ( $maybeCategory ) {
wp_redirect( get_term_link( $maybeCategory ) );
exit;
}
});
This kind of code could be added to a custom plugin or the theme's functions.php
file.