WordPress上传附件之后会自动生成附件页面,如何禁止附件页面呢?我们可以禁止附件页面,使附件页面重定向 (301) 以发布父级(如果有), 如果不是,则重定向(302)到主页。
在WordPress主题文件functions.php
中或者使用Code Snippets插件添加自定义代码:
function sar_attachment_redirect() { global $post; if ( is_attachment() && isset( $post->post_parent ) && is_numeric( $post->post_parent ) && ( 0 !== $post->post_parent ) ) { // Is the post in trash? $parent_post_in_trash = get_post_status( $post->post_parent ) === 'trash' ? true : false; // Prevent endless redirection loop in old WP releases and redirecting to trashed posts if an attachment page is visited when parent post is in trash. if ( $parent_post_in_trash ) { // Theme 404 template available? $theme_404_template = locate_template( '404.php' ); if ( ! empty( $theme_404_template ) ) { global $wp_query; $wp_query->set_404(); status_header( 404 ); nocache_headers(); require get_404_template(); exit; } else { wp_die( 'Page not found.', '404 - Page not found', 404 ); exit; } } // Redirect to post/page from where attachment was uploaded. wp_safe_redirect( get_permalink( $post->post_parent ), '301' ); exit; } elseif ( is_attachment() && isset( $post->post_parent ) && is_numeric( $post->post_parent ) && ( $post->post_parent < 1 ) ) { // Redirect to home for attachments not associated to any post/page. wp_safe_redirect( get_bloginfo( 'wpurl' ), '302' ); exit; } } add_action( 'template_redirect', 'sar_attachment_redirect', 1 );