These rewrite rules are killing me. It is probable something little, but I can't find it.

I have a custom post type called 'tournament', it's permalink structure looks like


For this custom post type everything works fine.

Now I have created a second custom post type 'match'. I set hierarchy to false. I added a meta-box to match where I can select the tournament and store it as post_parent.

Now I want its permalink structure to look like:


I use the post_type_link hook to add a filter that creates the permalink I want and the init hook to add the rewrite rule. The permalink is created as expected, but when using the rewrite rule, I keep getting 404's.

I flushed the rewrite rules both in code and manually.
I checked the regex and it's valid.
I suspect it is the redirect string, but I'm not sure.
Any suggestions or ideas?

function rat_match_post_type_link( $link, $post, $leavename, $sample ){

    if ( $post->post_type == 'match' ){

        $parent = get_post($post->post_parent);

        $season = get_post_meta( $parent->ID, 'rat-tournament-season', true);

        error_log (home_url( $season . '/' . $parent->post_name . '/match/' . $post->post_name));

        return home_url( $season . '/' . $parent->post_name . '/match/' . $post->post_name);
    } else {
        return $link;
add_filter('post_type_link', 'rat_match_post_type_link', 10, 4);

function rat_match_rewrite_rules()
add_action('init', 'rat_match_rewrite_rules');

Note: I know I need to fix the post type link function in case there is no parent.

EDIT (8-feb-2019)

While trying to investigate further I observed the following:

When I access:


The result is:


And the latter results in a 404.

  • 1
    have you tried setting match to just the match slug? Not sure why you’re inserting a different post type in there, especially since you say match is not hierarchical. If you need to pass tournament, you might have to put it in a custom query var so WP knows which post type you are actually trying to query. – Milo Jan 29 at 14:12
  • Yes I did, that was an older attempt when I did have match as with a hierarchy to tournament. I updated the post to show your suggestion. The result (404) remains the same – BasvdM Jan 30 at 15:21
  • Your rewrite rule works for me when I test it with an existing post type. Without knowing all of the details of the rest of your code, I can't say what the issue may be. – Milo Jan 30 at 16:28
  • One quick question, did you specify a slug for your post type? – BasvdM Feb 8 at 12:21

Your Answer

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

Browse other questions tagged or ask your own question.