WordPress CPT & Custom Taxonomy with the SAME Permalink Structure

Permalink Structure Function

This function constructs the permalink for the ‘guide’ post type, including all hierarchical terms, with added spaces for style consistency:

function xx_guide_permalink_structure($post_link, $post) {
    if ( 'guide' === $post->post_type && $terms = get_the_terms( $post->ID, 'guide-category' ) ) {
        usort( $terms, function( $a, $b ) { return $a->parent - $b->parent; } ); // Sort terms by parent
        $category_links = array();
        foreach ( $terms as $term ) {
            if ( ! empty( $term->parent ) ) {
                $parent_term = get_term( $term->parent, 'guide-category' );
                if ( ! in_array( $parent_term->slug, $category_links ) ) {
                    $category_links[] = $parent_term->slug; // Add parent term slug if not already added
                }
            }
            $category_links[] = $term->slug; // Add current term slug
        }
        $permalink = home_url( '/guides/' . implode( "https://wordpress.stackexchange.com/", $category_links ) . "https://wordpress.stackexchange.com/" . $post->post_name . "https://wordpress.stackexchange.com/" );
        return $permalink;
    }
    return $post_link;
}
add_filter( 'post_type_link', 'xx_guide_permalink_structure', 10, 2 );

Rewrite Rules Function

This function sets up the custom rewrite rules to correctly interpret the URL structure for posts and taxonomy archives:

function xx_cpt_permalink_rewrite_rules() {
    // For posts (deep nesting allowed)
    add_rewrite_rule(
        '^guides/(([^/]+/)+)([^/]+)/?$',
        'index.php?guide-category=$matches[1]&post_type=guide&name=$matches[3]',
        'top'
    );

    // For taxonomy archive (deep nesting allowed)
    add_rewrite_rule(
        '^guides/(([^/]+/)+)?/?$',
        'index.php?taxonomy=guide-category&term=$matches[1]',
        'top'
    );
}
add_action( 'init', 'xx_cpt_permalink_rewrite_rules' );

Remember to flush the permalink settings.

deneme bonusudeneme bonusu veren sitelerpulibet girişOnwin Güncel Giriştürkçe altyazılı pornocanlı bahis casino