Is it possible to list post attachments in a sub URL endpoint with a dedicated template?

I think I found it myself. Now I’ve successfully managed to add a /photos endpoint to a permalink URL, such as:

http://mywordpressite.com/projects/a-project/photos

And then a custom template, photos.php will load and show – with access to the global $post variable.

Helpful links:

In my functions.php I added functions for the single_template and query_vars filters and added a photos endpoint with the handy add_rewrite_endpoint() function.

// Permalink rewrites/add endpoints
add_filter( 'single_template', 'project_attachments_template' );
add_filter( 'query_vars', 'add_query_vars');

// You may need to go to wp-admin > Settings > Permalinks and 
// save the changes in order to flush rewrite rules to activate.
add_rewrite_endpoint('photos', EP_PERMALINK);

Further down in the file:

/**
*   Add the 'photos' query variable so WordPress
*   won't mangle it.
*/
function add_query_vars($vars){
    $vars[] = "photos";
    return $vars;
}


/**
*   From http://codex.wordpress.org/Template_Hierarchy
*
*   Adds a custom template to the query queue.
*/
function project_attachments_template($templates = ""){
    global $wp_query;

    // If the 'photos' endpoint isn't appended to the URL,
    // don't do anything and return
    if(!isset( $wp_query->query['photos'] ))
        return $templates;

    // .. otherwise, go ahead and add the 'photos.php' template
    // instead of 'single-{$type}.php'.
    if(!is_array($templates) && !empty($templates)) {
        $templates = locate_template(array("photos.php", $templates),false);
    } 
    elseif(empty($templates)) {
        $templates = locate_template("photos.php",false);
    }
    else {
        $new_template = locate_template(array("photos.php"));
        if(!empty($new_template)) array_unshift($templates,$new_template);
    }

    return $templates;
}

Be sure to visit the Permalink page in wp-admin for the changes to take effect.

Leave a Comment