0

I'm trying to change my attachment page to just automatically redirect to the attachment. Here's what I've tried:

Get attachment ID and redirect to that URL:

$urlArr = wp_get_attachment_image_src($_GET['attachment_id'], 'full');

if(empty($urlArr))
    $url = wp_get_attachment_url($_GET['attachment_id']);
else
    $url = $urlArr[0];

wp_redirect($url, 301); exit; 

The redirect to a textual version of the image, I've tried to send extra headers but run into a problem that headers have already been set...

I've searched for it online but only found links where people want to redirect to a certain page, but I'm trying to redirect to the media itself, plugin free. I'm adding the above code directly into attachment.php template file.

1 Answer 1

2

You can't redirect after content has already been sent to the browser, hook an action before the template is loaded and do your redirect there.

function wpa_attachment_redirect(){
    if( is_attachment() ){
        // your code and redirect here
    }
}
add_action( 'template_redirect', 'wpa_attachment_redirect' );
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.