Site icon Hip-Hop Website Design and Development

Prioritise Pages over Taxonomy Term Root Archive, but not Taxonomy Term Child Archives

I have a custom taxonomy (projects) linked to several different custom post types (events, stories, tutorials, news, podcast), as well as pages.

[I KNOW, but that is how I need it to be]

And have bashed the permalinks so that we can have:

example.com/project-1-name/events/

example.com/project-2-name/events/event-details-page/

example.com/project-1-name/news/

example.com/project-2-name/contact-us-page/

etc etc etc…

All working great… apart from one thing.

when we enter example.com/project-1-name/ – I don’t want each project’s taxonomy term root archive to show, I want the ‘home’ page for each project (e.g. page /project-1-name/) to show instead.

This is the code I currently have, managing the project taxonomy permalinks and making sure that CPT child page links work. I think I just need to adapt it to catch when we’re on the project term archive and switch to display the page instead, but am stumped.

add_filter('post_link', 'projects_permalink', 10, 3);
add_filter('post_type_link', 'projects_permalink', 10, 3);
 
function projects_permalink($permalink, $post_id, $leavename) {
    if (strpos($permalink, '%projects%') === FALSE) return $permalink;
     
        // Get post
        $post = get_post($post_id);
        if (!$post) return $permalink;
 
        // Get taxonomy terms
        $terms = wp_get_object_terms($post->ID, 'projects');   
        if (!is_wp_error($terms) && !empty($terms) && is_object($terms[0])) $taxonomy_slug = $terms[0]->slug;
        else $taxonomy_slug = '';
 
    return str_replace('%projects%', $taxonomy_slug, $permalink);
}