• I found a ton of articles / or third party plugins that make it possible to add a taxonomy in a cpt permalink, this works fine. But I can’t find anything on how to handle cpt permalinks if no taxonomy is set.

    With the taxonomy set I get custom-post-type/tax-name/post-name, but if it’s not set I keep getting custom-post-type/%tax-name%/post-name. I’m sure this can be fixed, but I don’t seem to be able to do so.

    The code from this article works fine, I tried in step 4 to simple add this.

    if ( $terms ) {
    return str_replace( ‘%tourist%’ , $terms[0]->slug , $post_link );
    } else {
    return str_replace( ” , $terms[0]->slug , $post_link );
    }

    This results in a 404 when I try to access custom-post-type/post-name. I guess this is because the rewrite in step 2 is set to:

    ‘rewrite’ => array(‘slug’ => ‘attraction/%tax-name%’)

    So in my mind the ‘rewrite’ would need to be set dynamically based on whether or not a taxonomy exists for a post, but I have no idea how to do this. Assuming that’s the way to fix this.

    Anyone any suggestions how to best deal with this?

Viewing 1 replies (of 1 total)
  • Moderator bcworkz

    (@bcworkz)

    We cannot have dynamic rewrite rules, it’d be something akin to “pulling oneself up by their bootstraps.”

    What you could do is implement two different rewrite rules so that one or the other will exclusively match each type of request. Presumably your CPT registration already implements the assigned taxonomy term condition. So you need an additional rule to match the unassigned condition. Add one with add_rewrite_rule().

    After adding the appropriate code, visit the permalinks settings screen to cause all rewrite rules to be regenerated. No need to save anything, loading the screen is enough.

Viewing 1 replies (of 1 total)
  • The topic ‘Optional taxonomy in cpt permalink’ is closed to new replies.