Last active
May 10, 2022 07:36
-
-
Save orvn/8461c115a9f08e7d7757b4f7b9f02621 to your computer and use it in GitHub Desktop.
Wordpress redirect attachment page to parent
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Redirect an attachment page to its parent. Opening the actual attachments is still valid | |
add_action( 'template_redirect', 'void_attachment_parent', 1 ); | |
if (!function_exists('void_attachment_parent')) : | |
function void_attachment_parent() { | |
global $post; | |
if ( is_attachment()): | |
// Optionally check file type and perform redirect for some files only. | |
// $filetype = wp_check_filetype( wp_get_attachment_url()); | |
if ( isset( $post->post_parent ) && | |
is_numeric( $post->post_parent ) && | |
( $post->post_parent !== 0 ) && | |
get_post_status( $post->post_parent ) !== 'trash' | |
) : | |
wp_safe_redirect( get_permalink( $post->post_parent ), 301 ); | |
exit(); | |
wp_reset_postdata(); | |
endif; | |
endif; | |
} | |
endif; | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment