Code comes from the codex:

<?php wp_redirect( get_permalink( $post->post_parent )); exit; ?>

I added the above, in an empty attachment.php page. When I visit an attachment page (eg. http://example.com/?attachment_id=2071) I get the error:

"This webpage has a redirect loop ERR_TOO_MANY_REDIRECTS"



Based on the answer given, I updated my code to:

if($post->post_parent != 0):

That way if the post_parent == 0, it will go back to the home page. I don't know if I should be catching for anything else. But this seems to work.

Thanks Ignat B. for explaining what was going on. I have a few attachments that have post_parent = 0. And it just happened that the link I was trying out was one of them.


1 Answer 1


Considering WordPress Codex, and WordPress Template Hierarchy - attachments stores as post records.

Your code is making a loop redirection to the same page. The most reasonable case is:

Your $post->post_parent equal to 0. If you'll make a var_dump(get_permalink($post->post_parent));, youll notice that the output would be the same page url.

  • Shouldn't media attachments never have post_parent = 0?
    – gdaniel
    Commented Aug 27, 2015 at 16:59

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.