I need the following url structures for my Custom Posttype and Custom Taxonomy. Can anyone please help in achieving them? Spent a lot of time but failed. Ton of thanks in advance.
- Post URL: https://www.domain.com/interventions/taxonomy-slug/post-slug/ (Achieved)
- Post Archive: https://www.domain.com/interventions/ (Achieved)
- Term URL: https://www.domain.com/interventions/taxonomy-slug/ (Need this)
Here's my setup
add_action( 'init', 'custom_post_type_intervention' );
function custom_post_type_intervention(){
$labels = array(
'name' => 'Interventions',
'singular_name' => 'Intervention',
'add_new' => 'Add Intervention',
'add_new_item' => 'New Intervention',
'edit_item' => 'Edit Intervention',
'all_items' => 'All Interventions',
'menu_name' => 'Interventions'
);
$args = array(
'labels' => $labels,
'public' => true,
'publicly_queryable' => true,
'show_ui' => true,
'show_in_menu' => true,
'show_in_rest' => true,
'query_var' => true,
'taxonomies' => array( 'intervention_cat' ),
'has_archive' => 'interventions',
'show_in_nav_menus' => true,
'menu_position' => 6,
'menu_icon' => 'dashicons-rest-api',
'supports' => array( 'title', 'editor', 'author', 'revisions' ),
'rewrite' => array( 'slug' => 'interventions/%intvn-cat%', 'with_front' => false )
);
register_post_type( 'intervention', $args );
unset( $args, $labels );
$labels = array(
'name' => 'Categories',
'singular_name' => 'Category'
);
$args = array(
'labels' => $labels,
'hierarchical' => true,
'show_in_nav_menus' => true,
'show_in_rest' => true,
'rewrite' => array( 'slug' => 'interventions', 'with_front' => false ),
'default_term' => array( 'name' => 'Uncategorized', 'slug' => 'uncategorized' )
);
register_taxonomy( 'intervention_cat', 'intervention', $args );
unset( $args, $labels );
function intervention_custom_post_slug( $post_link, $post ){
if( 'intervention' === $post->post_type ){
$terms = wp_get_object_terms( $post->ID, 'intervention_cat' );
if( $terms ){
return str_replace( '%intvn-cat%', $terms[0]->slug, $post_link );
}else{
return str_replace( '%intvn-cat%', 'uncategorized', $post_link );
}
}
return $post_link;
}
add_rewrite_tag( '%intvn-cat%', '(.+)' );
add_filter( 'post_type_link', 'intervention_custom_post_slug', 1, 3 );
//add_rewrite_rule( '^interventions/(.*)/?$', 'index.php?intervention_cat=$matches[1]', 'top' );
}