Skip to content

Instantly share code, notes, and snippets.

@lucprincen
Last active December 20, 2015 13:29
Show Gist options
  • Save lucprincen/0779fccc731873675bab to your computer and use it in GitHub Desktop.
Save lucprincen/0779fccc731873675bab to your computer and use it in GitHub Desktop.
add_filter('pre_get_posts', 'diiish_build_attachment_query');
function diiish_build_attachment_query( $query ){
if( !is_admin() ){
global $wp;
if( preg_match( '/^media\/(.*)/', $wp->request ) ) {
$req = explode( '/', $wp->request );
$id = $req[1];
$query->set('name', '');
$query->set('error', '');
$query->set('post_type', 'attachment');
$query->set('is_attachment', true );
$query->set('custom_attachment_url', $id );
$query->is_attachment = true;
$query->is_single = false;
$query->is_singular = false;
}
}
return $query;
}
if( !is_admin() ){
add_filter( 'posts_request', 'diiish_post_select' );
}
function diiish_post_select( $req ){
global $wp_query;
if( isset( $wp_query->query_vars['custom_attachment_url'] ) ){
$id = $wp_query->query_vars['custom_attachment_url'];
return "SELECT wp_posts.* FROM wp_posts WHERE 1=1 AND wp_posts.ID = ".$id." AND wp_posts.post_type = 'attachment' ORDER BY wp_posts.post_date DESC";
}
return $req;
}
add_action( 'template_redirect', 'diiish_redirect_template' );
function diiish_redirect_template(){
if( !is_admin() ){
global $wp_query;
if( isset( $wp_query->query_vars['custom_attachment_url'] ) ){
$id = $wp_query->query_vars['custom_attachment_url'];
if( isset( $wp_query->post ) ){
$mime = $wp_query->post->post_mime_type;
$mime = explode( '/', $mime );
$template = $mime[0].'.php';
locate_template( array( $template, 'attachment.php', 'single.php', 'index.php' ), true );
die();
}
}
}
}
@lucprincen
Copy link
Author

I changed the 'wp' action to 'template_redirect'. This didn't work before but by eleminating a few attachment_id variables in pre_get_posts and get in our own variable; it now works without 'having to prevent a redirect'. it's more streamlined.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment