0

In my current case, the system try to find a page and show 404 if it does not find. I would like with the same url... like https://example.com/{{slug}}/

  1. Check if a page with this slug exists :
      • Yes - show the page
      • No - switch to the category page (with same slug)
      • No category page -> show page 404

What is the best recommandanted way to do this in WP?

0

you can do this in the file 404.php, start the file with some kind of check if is page, if so redirect to that link, if is not page redirect to category page with that slug else just let the 404.php page

this is in the file 404.php

0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.