Add term slug in URL of custom post type details page

You need to update below line at where you have register a custom post type using register_post_type function.

‘rewrite’ => array(‘slug’ => ‘movies/%cat%’)

To change permalink dynamically of post type you have to add below code in functions.php file :

function change_link( $post_link, $id = 0 ) {
    $post = get_post( $id );
    if( $post->post_type == 'movies' ) 
    {
       if ( is_object( $post ) ) {
          # assume that 'available-for' is slug of your taxonomy 
          $terms = wp_get_object_terms( $post->ID, array('available-for') );
          if ( $terms ) {
             return str_replace( '%cat%', $terms[0]->slug, $post_link );
         }
      }
    }
    return   $post_link ;
}
add_filter( 'post_type_link', 'change_link', 1, 3 );

//load the template on the new generated URL otherwise you will get 404's the page



   function generated_rewrite_rules() {
       add_rewrite_rule(
           '^movies/(.*)/(.*)/?$',
           'index.php?post_type=movies&name=$matches[2]',
           'top'
       );
    }
    add_action( 'init', 'generated_rewrite_rules' ); 
  • domain.com/movies/{%selected term%}/avengers-endgame/

To use Term first, you have change to this.

‘rewrite’ => array(‘slug’ => ‘%cat%/movies’)

function change_link( $post_link, $id = 0 ) {
    $post = get_post( $id );
    if( $post->post_type == 'movies' ) 
    {
       if ( is_object( $post ) ) {
          # assume that 'available-for' is slug of your taxonomy 
          $terms = wp_get_object_terms( $post->ID, array('available-for') );
          if ( $terms ) {
             return str_replace( '%cat%', $terms[0]->slug, $post_link );
         }
      }
    }
    return   $post_link ;
}
add_filter( 'post_type_link', 'change_link', 1, 3 );

function movie_cpt_generating_rule($wp_rewrite) {
    $rules = array();
    $terms = get_terms( array(
        'taxonomy' => 'available-for',
        'hide_empty' => false,
    ) );

$post_type="movies";
foreach ($terms as $term) {    

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

}
// merge with global rules
$wp_rewrite->rules = $rules + $wp_rewrite->rules;
}
add_filter('generate_rewrite_rules', 'movie_cpt_generating_rule');

After that, you need to flush rewrites permalinks, goto the wp-admin > Settings > permalinks. just update permalink setting using “Save Changes” button.

it’ll return urls like below :

  • domain.com/{%selected term%}/movies/avengers-endgame/

Thank you!