how to add custom taxonomy term slug to a custom post type WP?

26 views Asked by At

So, I have a custom post type name activity and a custom taxonomy name season. Both are created from ACF.

The url slug for activity I want to become like this :

doman.com/${season}/activity/post-name

the taxonomy term have 2 terms. sommer and winter.

here's what I've been to do :

  • create post type activity with acf, here's the setting for permalink enter image description here
  • create taxonomy season. I just set the slug to default key, like this : enter image description here
  • "change" the %season% in code , like this :
function custom_post_type_permalink($permalink, $post, $leavename) {
    // Check if the post is of the custom post type 'activity'
    if ($post->post_type == 'activity') {
        // Get the season taxonomy terms for the post
        $terms = wp_get_post_terms($post->ID, 'season');
        // If there's a season term, append it to the permalink
        if (!empty($terms) && !is_wp_error($terms)) {
            $season_slug = $terms[0]->slug;
            $permalink = str_replace( '%season%' , $season_slug , $permalink );
        }
    }
    return $permalink;
}
add_filter('post_type_link', 'custom_post_type_permalink', 10, 3);

the problem with this is that :

  • all post type pages (default wordpress) become 404 page not found
  • if I don't specify the season, it should be return the page. not 404. so in this case the %season% is optional.

how to achieve this?

0

There are 0 answers