To get all posts ordered by their template you need two functions: one for the query, and one to add a custom order.
Get the posts
function get_posts_by_template()
{
add_filter( 'posts_orderby', 'orderby_template' );
$query = new WP_Query(
array(
//'meta_key' => '_wp_page_template',
'post_type' => 'any',
'orderby' => 'title',
'order' => 'ASC',
'posts_per_page' => -1, // dangerous
'meta_query' => array(
array(
'key' => '_wp_page_template',
'value' => '',
'compare' => '!='
)
)
)
);
if ( empty ( $query->posts ) )
return FALSE;
return $query->posts;
}
Change the order
function orderby_template( $orderby )
{
global $wpdb;
remove_filter( current_filter(), __FUNCTION__ );
$orderby = $wpdb->postmeta . '.meta_value DESC, ' . $orderby;
return $orderby;
}
For a nice overview we could use something like this:
function list_posts_by_template()
{
$posts = get_posts_by_template();
if ( ! $posts )
return print 'no posts with a template found';
static $template="";
foreach ( $posts as $post )
{
$post_template = get_post_meta( $post->ID, '_wp_page_template', TRUE ) . '<br>';
if ( $post_template !== $template )
{
print "<h2>$post_template</h2>";
$template = $post_template;
}
printf(
'<p><a href="https://wordpress.stackexchange.com/questions/96976/%1$s">%2$s</a></p>',
get_permalink( $post->ID ),
esc_html( $post->post_title )
);
}
}