0

I have two custom post types

  1. colors
  2. shapes

I have a post called "red" under the custom post type "colors". The default URL for this post would be

example.com/colors/red

Now I want to make it accessible from the following URL as well

example.com/shapes/red

The closest I came with is to add a filter to change_404_template (as I receive a 404 for above url) and forcefully inject the single.php file with some hacky code.

Is there a way more standard method to do this ?

1 Answer 1

0

Found the way, For anyone looking for a method in the future I'll mention how I made it work.

add_action( 'parse_request', function($query){  
    $post_type = $post_name = NULL;

    if (isset($query->query_vars['post_type']) && in_array($query->query_vars['post_type'], ['colors', 'shapes'])) {
        $post_type = $query->query_vars['post_type'];
        $post_name = $query->query_vars['name'];
    } elseif (isset($query->query_vars['pagename']) &&  isset($query->request) && isset(explode('/', $query->request)[0]) && in_array(explode('/', $query->request)[0], ['slug-with-no-post-type', 'another-slug-with-no-post-type'])) {
        $division = explode('/', $query->request)[0];
        if (isset(explode('/', $query->request)[1])) $post_type = explode('/', $query->request)[1];
        unset($query->query_vars['pagename']);
    }

    if($post_type && $post_name){
        if ($post = get_page_by_path($post_name, 'OBJECT', ['colors', 'shapes'])) {
            if (isset($post->post_type) && $post->post_type != $post_type) {
                $query->query_vars['post_type'] = $post->post_type;
                $query->query_vars['post_type_template'] = $post_type;
                $query->query_vars['name'] = $post_name;
            }
        }
    }
});

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.