Get URL for specific post type and current tag

I have a number of custom post types as well as a custom taxonomy. I created an archive page for the taxonomy which lists each connected post, so all good there. What I would like to achieve is the following…

On my single template for that taxonomy (I’ve called it Topics), say if the topic was ‘cancer’, I would like a dropdown select menu or list of links to each custom post type WITH that taxonomy label. In other words, if I’m showing all the posts tagged with ‘cancer’ for every post type (which I currently have), that dropdown or link list at the top of the page would allow me to only show the tagged posts for each post type, as in the following:

Showing posts with topic: cancer

Select a post type to view posts with this topic:

Post type name 1 (link)
Post type name 2 (link)
Post type name 3 (link)

(all posts tagged with cancer already display here...)

Post type 1, when clicked, loads the single taxonomy page again but only lists the posts tagged with ‘cancer’ for that post type. This would apply to any of the few dozen tags for that custom taxonomy, so I can’t hard-code the URL. It needs to be dynamic.

I hope this makes sense. I’ve searched for two days on this and so far have come up with nothing. Any help or direction would be appreciated. Unfortunately, the project I’m working on is gated and I can’t share any links. I’m also using the Custom Post Type UI plugin (not by choice) and I know that plugin doesn’t work well with taxonomies but I’m hoping my hands aren’t tied here.

Cheers.

2 Answers
2

If the URL to the ‘cancer’ taxonomy term in your example looked like this:

yourwebsite.com/topics/cancer/

then you could filter these results by post type with a URLs structured like this:

yourwebsite.com/topics/cancer/?post_type=question

Just put this in functions.php

add_filter( 'pre_get_posts', 'wp123_post_type_by_taxonomy' );
function wp123_post_type_by_taxonomy( $query ) {
    if( is_tax( 'topics' ) && $query->is_main_query() ) {

        // get all post types:
        $post_types = get_post_types();

        // or add specific post types:
        // $post_types = array( 'post_type_1', 'post_type_2' );

        if ( !empty( $_GET['post_type'] ) && post_type_exists( $_GET['post_type'] ) ) {
            // show only results for this post type
            $query->set( 'post_type', $_GET['post_type'] );
        }

    }
}

Leave a Comment