Creating custom permalinks for certain categories in WordPress

We had to create a custom permalink for a certain category, this is how it’s done.

For a certain client, we had to create a custom permalink structure for a certain category of posts. We could’ve created a custom post type and that would’ve accomplished that task as well. However, that was out of the scope of the project.

Here is what we ended up with:

add_filter( 'category_link', 'custom_category_permalink', 10, 2 );
function custom_category_permalink( $link, $cat_id ) {
    $slug = get_term_field( 'slug', $cat_id, 'category' );
    if ( ! is_wp_error( $slug ) && 'testimonials' === $slug ) {
        $link = home_url( user_trailingslashit( '/testimonials/', 'category' ) );
    }
    return $link;
}

add_action( 'init', 'custom_rewrite_rules' );
function custom_rewrite_rules() {
    add_rewrite_rule(
        'testimonials(?:/page/?([0-9]{1,})|)/?$',
        'index.php?category_name=testimonials&paged=$matches[1]',
        'top' // The rule position; either 'top' or 'bottom' (default).
    );

    add_rewrite_rule(
        'testimonials/([^/]+)(?:/([0-9]+))?/?$',
        'index.php?category_name=testimonials&name=$matches[1]&page=$matches[2]',
        'top' // The rule position; either 'top' or 'bottom' (default).
    );
}

This is just a starting point. Going through the WordPress Codex, you will find that the possibilities are endless.


References: The snippet above has been referenced from:

  1. https://wordpress.stackexchange.com/questions/296699/give-specific-category-its-own-permalink-structure/296703#296703

Leave a Reply

Your email address will not be published. Required fields are marked *