1

I have a post type called worksheets and I have a taxonomy called worksheets_category.

I want to have the following url structure for both.

worksheets - example.com/worksheets/sample-single-page

worksheets category - example.com/worksheets/sample-category

Any help would be appreciated. Thanks!

0

There is no easy way, because it will cause conflicts. This means you have to solve those conflicts yourself and implement some logic, that will determine what to show.

Here's sample approach:

add_filter( 'term_link', 'repair_categories_link', 10, 3 );
add_action( 'parse_request', 'repair_links' );
add_action( 'pre_get_posts', 'repair_query_post_type' );

// First we have to modify links for categories
function repair_categories_link( $url, $term, $taxonomy ) {
    if ( 'worksheets_category' == $taxonomy ) {
        $url = str_replace( site_url( '/worksheets_category/' ), get_post_type_archive_link( 'worksheets' ), $url );
    }
    return $url;
}

// Then we have to solve conflicts - if given category exists, show category and not a post
function repair_links( $wp ) {
    if ( array_key_exists( 'worksheets', $wp->query_vars) && $wp->query_vars['worksheets'] ) {
        if ( term_exists($wp->query_vars['worksheets'], 'worksheets_category') ) {
            $wp->query_vars['worksheets_category'] = $wp->query_vars['worksheets'];
            unset( $wp->query_vars['worksheets'] );
            unset( $wp->query_vars['name'] );
            unset( $wp->query_vars['post_type'] );
        }
    }
}

// And we have to fix post type 
function repair_query_post_type( $query ) {
    if ( ! is_admin() && $query->is_main_query() && get_query_var('worksheets_category') ) {
        $query->set( 'post_type', 'worksheets' );
    }
}
| improve this answer | |
  • Thanks for your answer but unfortunately it doesn't work. I tried your code. – marccaps Apr 24 at 7:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.