How to check if last uri segment is a custom post type or taxonomy term?

To see how we can make this work, have a read through the Query Overview Codex page, particularly the What Plugins can Modify section:

Modify the query specification, after variable values are saved (request filter or parse_request action; if you want to use conditional tag tests, use the parse_query or pre_get_posts action, as these run after the is_ variables are set).

In this case, we want to filter request, which will be an array of the query vars which were set by the parse_request method of the WP class (scroll to the end of this function to see where the filter is applied).

In our filter, we’ll check if gallery_cat is set, and if the requested term is actually an existing gallery_cat term. If it’s not, we’ll assume it’s a gallery post, and reset the query vars to make WordPress query for the post instead of the term. To do that we need to set 3 different query vars- gallery, name, and post_type.

function wpd_gallery_request_filter( $request ){
    if( array_key_exists( 'gallery_cat' , $request )
        && ! get_term_by( 'slug', $request['gallery_cat'], 'gallery_cat' ) ){
            $request['gallery'] = $request['gallery_cat'];
            $request['name'] = $request['gallery_cat'];
            $request['post_type'] = 'gallery';
            unset( $request['gallery_cat'] );
    }
    return $request;
}
add_filter( 'request', 'wpd_gallery_request_filter' );

Leave a Comment