Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 days ago.
Improve this questionI have a custom post type and a custom taxonomy created with ACF Pro. The post type:
And the taxonomy:
Then in functions.php
, I have this code:
add_action(
'init',
function() {
add_rewrite_rule(
'^(?:tour-category-1|tour-category-2|tour-category-3)/([^/]+)/?$',
'index.php?post_type=tour&name=$matches[1]',
'top',
);
},
);
add_filter(
'post_type_link',
function(string $post_link, WP_Post $post) {
static $placeholders_to_taxonomies = [
'%tourcategory%' => 'tour-category',
];
foreach ($placeholders_to_taxonomies as $placeholder => $taxonomy) {
if (str_contains($post_link, $placeholder)) {
$term = get_primary_term($taxonomy, $post->ID);
$replace = 'uncategorized';
if ($term instanceof WP_Term) {
$replace = $term->slug;
}
$post_link = str_replace($placeholder, $replace, $post_link);
}
}
return $post_link;
},
10,
2,
);
function get_primary_term(string $taxonomy, int $post_id): WP_Term|false
{
$primary_term = false;
$terms = get_the_terms($post_id, $taxonomy);
$terms = is_wp_error($terms) ? [] : $terms;
$terms = $terms ?: [];
if ($terms) {
[$primary_term] = $terms;
}
}
(For the call to add_rewrite_rule
, the category slugs in the regex are not the actual categories that are being used on the site.)
This works, but every time the client adds a category I have to add the new category slug to the regex. I could change it to retrieve all the categories and add a rewrite rule for each one, but I don't know if this would slow down the site or if there is a better approach than that.