Skip to content

Instantly share code, notes, and snippets.

@ActuallyConnor
Last active January 20, 2021 16:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ActuallyConnor/111cf604ca0108a9b56a338604da0501 to your computer and use it in GitHub Desktop.
Save ActuallyConnor/111cf604ca0108a9b56a338604da0501 to your computer and use it in GitHub Desktop.
WP URL rewrite to follow structure of example.com/{post_type}/{taxonomy_term}/{post_name}
<?php
/**
* This assumes you've created a CPT and a custom taxonomy that functions like a tag.
* You simply attach the taxonomy term to a specific post and voila.
* Refresh your permalinks!
* My recommendation would be to use ACF to only allow one tag to be set per post.
*/
/**
* Filter the custom post type link to create prettier URLs that follow the structure:
* /{post_type}/{taxonomy_term}/{post_name}
*/
add_filter( 'post_type_link', function( $link, $post = 0 ) {
$post_type = get_post_type( $post );
if ( 'content_series' !== $post_type ) {
return $link;
}
$post_obj = get_post( $post );
$post_type_obj = get_post_type_object( $post_type );
$post_cat = get_the_terms( $post_obj, 'content_series_cat' )[ 0 ];
$post_link = sprintf( "/%s/%s/%s", $post_type_obj->rewrite[ 'slug' ], $post_cat->slug, $post_obj->post_name );
return home_url( $post_link );
}, 10, 2 );
/**
* Adding rewrite rules for:
* /{post_type}/{taxonomy_term}/{post_name}
* /{post_type}/{taxonomy_term}
*/
add_action( 'init', function() {
add_rewrite_rule( 'content-series/([^/]*)/([^/]*)', 'index.php?content_series_cat=$matches[1]&content_series=$matches[2]', 'top' );
add_rewrite_rule( 'content-series/([^/]*)', 'index.php?content_series_cat=$matches[1]', 'top' );
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment