Change CPT permalink to use the category

I have a CPT called teachers and a custom taxonomy called teacher type.

I’m using the code below to rewrite the url for the CPT and instead of being like: website.com/teachers/post1

it changes the slug to use the category: website.com/teacher-type/post1

This is working correctly but now I need to add another taxonomy (year) to the CPT and to the slug and I need it to be like this:

website.com/teacher-type/year/post1

The code I’m using is compatible with WPML.

This is it:

function resources_cpt_generating_rule($wp_rewrite) {
global $sitepress, $sitepress_settings;

$has_filter = remove_filter( ‘terms_clauses’, array( $sitepress, ‘terms_clauses’ ) );
$auto_adjust_ids = $sitepress_settings[‘auto_adjust_ids’];
$sitepress_settings[‘auto_adjust_ids’] = 0;

$rules = array();
$terms = get_terms( array(
‘taxonomy’ => ‘teacher_types’,
‘hide_empty’ => false,
) );

$post_type = ‘teachers’;

foreach ($terms as $term) {

$rules[ $term->slug . ‘/([^/]*)$’] = ‘index.php?post_type=’ . $post_type. ‘&name=$matches[1]’;

}

// merge with global rules
$wp_rewrite->rules = $rules + $wp_rewrite->rules;

if ( $has_filter ) {
add_filter( ‘terms_clauses’, array( $sitepress, ‘terms_clauses’ ) );
}
$sitepress_settings[‘auto_adjust_ids’] = $auto_adjust_ids;

}
add_filter(‘generate_rewrite_rules’, ‘resources_cpt_generating_rule’, 20);

function change_link( $permalink, $post ) {

if( $post->post_type == ‘teachers’ ) {
$resource_terms = get_the_terms( $post, ‘teacher_types’ );
$term_slug = ”;
if( ! empty( $resource_terms ) ) {
foreach ( $resource_terms as $term ) {
// The featured resource will have another category which is the main one

$term_slug = $term->slug;
break;
}
}
$permalink = apply_filters( ‘wpml_permalink’, trailingslashit( get_home_url() ) . $term_slug . ‘/’ . $post->post_name );
}
return $permalink;
}
add_filter(‘post_type_link’,”change_link”,10,2);

Any ideas on how to concatenate those two taxonomies in the url?

Thanks for your help!

Read more here:: Change CPT permalink to use the category

Leave a Reply

Your email address will not be published. Required fields are marked *