WordPress custom taxonomy URL rewrite on spelling errors

It also doesn’t matter which URL part is changed, except the last one.
So this still shows the content of the original page.

Yes, because your taxonomy’s rewrite is hierarchical with the permalink structure /treatment/<term slug> (e.g. /treatment/psychosomatic) or /treatment/<term slug>/<term slug>/... (if the term is a child term, e.g. /treatment/psychosomatic/psychosomatic-dysfunction), so as long as the current URL matches that structure and that the last <term slug> is a valid term slug, then the page would load normally.

how to change the behaviour so that misspelled URLs will cause a 404
error?

There is no taxonomy argument or admin setting that can do that, but you can use the pre_handle_404 filter like so: (you can add this to your theme functions file)

add_filter( 'pre_handle_404', 'my_pre_handle_404', 10, 2 );
function my_pre_handle_404( $preempt, $wp_query ) {
    // A list of taxonomy slugs.
    $taxonomies = array( 'treatment' );

    // Check if we're on the archive page for taxonomies in the above list.
    if ( $wp_query->is_tax( $taxonomies ) ) {
        // We need this to access the path of the current URL ($wp->request),
        // and note that the path does not include the trailing slashes.
        global $wp;

        // Get the original/correct term permalink.
        // e.g. https://example.com/treatment/parent/child/term-slug/
        $permalink = get_term_link( $wp_query->get_queried_object() );

        // Get the path in the above permalink.
        // e.g. treatment/parent/child/term-slug - traling slashes are trimmed
        $orig_path = trim( parse_url( $permalink, PHP_URL_PATH ), "https://wordpress.stackexchange.com/" );

        // Check if the above path matches the path of the current URL, and if
        // not, then we issue a 404 error.
        if ( $orig_path !== $wp->request ) {
            $wp_query->set_404();
        }
    }

    return $preempt;
}

If you want the code to work with the default category taxonomy, then change the $wp_query->is_tax( $taxonomies ) to $wp_query->is_tax( $taxonomies ) || $wp_query->is_category().

Leave a Comment