<?php

/*
Plugin Name: Query attachments
Description: Show attachments by type
Plugin URI: http://samm.dreamhosters.com/wordpress/plugins/
Author: Sam
Version: 0.1

=== Query attachments ===
Tags: attachments, archive
Requires at least: 2.5
Tested up to: 2.5.1
Stable tag: 

Here is a short description of the plugin.  This should be no more than 150 chars. No markup here.

== Description ==

This is the long description.  No limit, and you can use Markdown…

== Installation ==

This section describes how to install the plugin and get it working.

*/

/**
 * Prefix for attachment query permalinks.
 *
 * If you change this, click "Update" on the Permalinks admin panel
 **/
define( 'QA_PERMALINK_BASE', 'attachments' );

register_activation_hook( __FILE__, 'qa_flush_rules' );
register_deactivation_hook( __FILE__, 'qa_flush_rules' );
add_action('parse_query', 'qa_parse_query');
add_action('init', 'qa_init');
add_filter('rewrite_rules_array', 'qa_rewrite_rules_array');

function qa_rewrite_rules_array($rules) {
	//	Let WP build the rules, then append '&post_type=attachment' to end
	
	return $GLOBALS['wp_rewrite']->generate_rewrite_rules( $GLOBALS['wp_rewrite']->root . '/' . QA_PERMALINK_BASE . '/type/%post_mime_type%' , EP_ALL )
		+ array_map( 'qa_append' , $GLOBALS['wp_rewrite']->generate_rewrite_rules( $GLOBALS['wp_rewrite']->root . '/' . QA_PERMALINK_BASE , EP_ALL ))
		+ $rules;
}

function qa_append( $query ) {
	return $query . '&post_type=attachment';
}

function qa_init() {
	// query_posts('post_type=attachment&post_mime_type=audio&post_status=inherit');
	$GLOBALS['wp']->add_query_var('post_type');
	// $GLOBALS['wp']->add_query_var('post_mime_type'); // handled by add_rewrite_tag
	add_rewrite_tag( '%post_mime_type%', '(.+)' );
}


function qa_parse_query( &$wp_query ) {
	if ( 'attachment' ==  get_query_var('post_type') ) {
		set_query_var( 'post_status', 'inherit' );
		// Correct conditionals
		$wp_query->is_archive = true;
		$wp_query->is_home = false;
		$wp_query->is_singular = false;
	}
}

function qa_flush_rules() {
	$GLOBALS['wp_rewrite']->flush_rules();
}

?>