I think I solved my problem. So if you have your WordPress post permalink set to %category%/%postname%/
, and you want this for custom post type and taxonomy, you could prepare your rewrite links for all generated taxonomy terms (cat-a, cat-b etc.).
Code:
add_filter( 'rewrite_rules_array', function($rules) {
$categories = get_terms(['taxonomy' => 'success-category' ]);
foreach ($categories as $category){
$rules = array($category->slug.'/([^/]*)/?$' => 'index.php?success-category='.$category->slug.'&our-success=$matches[1]&post_type=our-success') + $rules;
}
return $rules;
});
I was trying the same with wpd_foo_rewrite_rule()
function, but it seems like there are no terms with ‘init’ action. So I have removed function wpd_foo_rewrite_rule()
I left function wpa_show_permalinks
unchanged.
There is only problem with new created terms, but if you flush_rewrite_rules() once, problem disappear.
Update
I ended with two more functions.
First for checking if term haven’t any relation and setting flag for future flush_rewrite_rules()
with update_option( 'success-category-flush-rewrite-rules', true );
add_action('added_term_relationship', 'flush_if_term_first_time_in_use', 10, 3);
function flush_if_term_first_time_in_use( int $object_id, int $tt_id, string $taxonomy ) {
if( $taxonomy !== 'success-category' ){
return;
}
if( get_term($tt_id)->count === 0 ){
update_option( 'success-category-flush-rewrite-rules', true );
}
}
Second only for execute flush_rewrite_rules()
function flush_rewrite_after_term_relation() {
if( get_option('success-category-flush-rewrite-rules') == true){
flush_rewrite_rules();
update_option( 'success-category-flush-rewrite-rules', false );
}
}
add_action( 'init', 'flush_rewrite_after_term_relation',1,1 );