0

I'm developing a plugin that will set up a new custom post type (tournament) and which creates posts for this CPT using an API that gets called using WP Cron. The CPT has a custom field called season that I want to use in the permalink.

I have set up the permalink as follows:

http://local.wordpress.test/tournament/2019/my-tournament-name

tournament is the post-type
2019 is the season
my-tournament-name is the post_name

I created the permalink with the following code:

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

    if ( $post->post_type == 'tournament' ){
        $season = get_post_meta( $post->ID, 'rat-tournament-season', true);
        return home_url( 'tournament/' . $season . '/' . $post->post_name );
    } else {
        return $link;
    }
 }
add_filter('post_type_link', 'rat_post_type_link', 10, 4);

Then I have added a rewrite rule to show the specific post

function rat_custom_post_type_rewrite_rules() {
    add_rewrite_rule(
        'tournament/[0-9]{4}/([^/]+)?$',
        '?post_type=tournament&page_name=$matches[1]',
        'top');
}
add_action('init', 'rat_custom_post_type_rewrite_rules');

I'm using flush_rewrite_rules() in my plugin activator and can confirm this gets called. I installed Rewrite Analyzer to debug the rewriting rule.

I tested and confirmed that the link http://local.wordpress.test/?tournament=my-tournament-name is working.

I have included debug statements in the rat_custom_post_type_rewrite_rules() function and they show up in the debug.log, so I know the function gets called.

My problem is that I can't find the rewrite rule in the list shown by Rewrite Analyzer. Any suggestions as to why this is?

Additional note: I haven't used add_rewrite_tag() for the season because I don't need it on the querystring.

1 Answer 1

1

It's not showing up because internal rewrites must point to index.php. This isn't your theme's index.php file, it's the main root WordPress bootstrap file. This is how WP detects what should be an internal rule (parsed in PHP) and an external rule (added to htaccess).

The other issue you will have is that page_name isn't a valid query var. For a custom post type, you can simplify this to:

'index.php?tournament=$matches[1]'
1
  • Thanks, that's it. I tried so many combinations, but missed this one
    – BasvdM
    Commented Jan 25, 2019 at 8:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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