WordPress tries to guess what post the user want to see by post name. That is what is making both example.com/new-bikes/ktm/duke/ktm-690-duke-2012/
and example.com/new-bikes/ktm/yamaha/ktm-690-duke-2012/
return the same and “correct” content.
What is important is that, if you see at the source code of example.com/new-bikes/ktm/yamaha/ktm-690-duke-2012/
, you can see the canonical URL correctly set to example.com/new-bikes/ktm/duke/ktm-690-duke-2012/
. User gets what he is looking for and search engines knows the canonical URL, so every one wins.
So, I don’t recommend to force a 404 error on example.com/new-bikes/ktm/yamaha/ktm-690-duke-2012/
and I think you should not worried about this.
Anyway, if you really want to avoid that URL, I would redirect the user to the canonical URL with a 301 status code instead of forcing a 404:
add_action( 'template_redirect', 'cyb_canonical_redirect' );
function cyb_canonical_redirect() {
global $wp;
if( is_singular() ) {
$id = get_queried_object_id();
$canonical_url = get_permalink( $id );
$current_request = site_url( $wp->request );
// Compare current request and canonical url
if( $canonical_url != $current_request) {
wp_redirect( $canonical_url, 301 );
exit();
}
}
}