admin管理员组

文章数量:1384438

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/worksheets/sample-single-page

worksheets category - example/worksheets/sample-category

Any help would be appreciated. Thanks!

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/worksheets/sample-single-page

worksheets category - example/worksheets/sample-category

Any help would be appreciated. Thanks!

Share Improve this question asked Apr 24, 2020 at 5:58 marccapsmarccaps 592 silver badges8 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 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' );
    }
}

本文标签: custom post typesHow to have the same url structure for both a CPT and a Taxonomy