Permalink Rewrite for Custom Taxonomy

I have added a custom taxonomy called ‘Boards’ with the following code

function add_custom_taxonomies() {

    register_taxonomy('board', 'post', array(
        'labels' => array(
            'name' => _x( 'Boards', 'taxonomy general name' ),
            ~snipped~
        ),
        'rewrite' => array(
            'slug' => 'board',
            'with_front' => false,
            'hierarchical' => true
        )
    ));
}

add_action( 'init', 'add_custom_taxonomies', 0 );

If I have 2 boards with the same name “My Board”, the urls will be
1) mydomain.com/boards/my-board/
2) mydomain.com/boards/my-board-2/

I would prefer to use the board/term ids so that the urls are
1) mydomain.com/boards/15/
2) mydomain.com/boards/16/

Possible?

1 Answer
1

There are a few parts to making this work.

First, we register the taxonomy:

function wpa69163_register_txonomy() {
    register_taxonomy('board', 'post', array(
        'labels' => array(
            'name' => _x( 'Boards', 'taxonomy general name' ),
        ),
        'rewrite' => array(
            'slug' => 'board',
            'with_front' => false
        )
    ));
}
add_action( 'init', 'wpa69163_register_txonomy', 0 );

Next, we have to add a filter to term_link to generate the URLs with term_id for our tax terms:

function wpa69163_term_link( $termlink, $term, $taxonomy ){
    if( 'board' == $taxonomy )
        return home_url() . '/board/' . $term->term_id . "https://wordpress.stackexchange.com/";
    return $termlink;
}
add_filter( 'term_link', 'wpa69163_term_link', 10, 3 );

And last, we have to intercept any queries for our tax terms and convert the board query var from ID back to slug so WordPress is able to load the correct posts:

function wpa69163_boards_query( $query ) {
    if( isset( $query->query_vars['board'] ) ):
        if( $board = get_term_by( 'id', $query->query_vars['board'], 'board' ) )
            $query->query_vars['board'] = $board->slug;
    endif;
}
add_action( 'parse_query', 'wpa69163_boards_query' );

Leave a Comment