Clean URL permalink for custom post type

I have a custom content type of photo_group which is a collection of photos.

I want to be able to go to mysite.com/photos and have that page dump out all of my photo groups.

Read More

How can I do this without making a “page” and setting the template? Or is that the approach I’ll have to take?

Thanks

Related posts

Leave a Reply

2 comments

  1. 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.

  2. You just need a custom taxonomy to do this. You don’t need to make a page for mysite.com/photos, it can be a taxonomy page. For example: create a custom taxonomy named “photos“.Then you can copy taxonomy.php to a taxonomy-photos.php as your custom taxonomy page template file.

    Check it on WordPress Codex: Custom Taxonomies Codex

    Some plugins can help you to create these custom taxonomies in a very easy way. Just find the one you like: http://wordpress.org/extend/plugins/search.php?q=Custom+Taxonomies

    Good Luck!