Clean URL permalink for custom post type

Romes,

The method you suggested will definitely work and is likely the easiest; however, I can definitely see cases in which this is not ideal. To accomplish this more “programmatically”, you would need to do the following:

1) Set a new query var

2) Generate a new rewrite rule to make sense of that query var

3) Redirect to a template when that query var is matched.

Here’s some code to help you along.

1: Add the query var

function query_vars( $public_query_vars ) {
    $public_query_vars[] = 'romes_var';
    return $public_query_vars;
}
add_filter( 'query_vars', 'romes_query_vars' );

2: Associate a rewrite rule to handle the query var

function romes_generate_rewrite_rules( $wp_rewrite ) {
    $new_rules = array();
    $new_rules['(photos)/?$'] = 'index.php?romes_var=$matches[1]';
    $wp_rewrite->rules = $new_rules + $wp_rewrite->rules;
}
add_action( 'generate_rewrite_rules', 'romes_generate_rewrite_rules' );

3: Detect the query var and redirect to a template

function romes_template_redirect() {
    if ( 'photos' == get_query_var( 'romes_var' ) ) {
        load_template( get_stylesheet_directory_uri() . '/template-photos.php' );
        exit();
    }
}
add_action( 'template_redirect', 'romes_template_redirect' );

This code isn’t specifically tested, but should get you most of the way. Be sure to flush your rewrite rules (simply visit the permalinks page) before you attempt to run your script with this code.

Leave a Comment