312026-01
禁用WordPress附件页面
/**
* 禁用WordPress附件页面
*/
add_action('init', function() {
// 1. 重定向附件页面
add_action('template_redirect', function() {
if (is_attachment()) {
global $post;
if ($post && $post->post_parent) {
wp_redirect(get_permalink($post->post_parent), 301);
} else {
wp_redirect(home_url(), 301);
}
exit;
}
});
// 2. 修改附件链接
add_filter('attachment_link', function($url, $post_id) {
return wp_get_attachment_url($post_id);
}, 99, 2);
// 3. 防止索引
add_action('wp_head', function() {
if (is_attachment()) {
echo '<meta name="robots" content="noindex,nofollow" />';
}
}, 1);
// 4. 清理重写规则
add_filter('rewrite_rules_array', function($rules) {
foreach ($rules as $rule => $rewrite) {
if (strpos($rewrite, 'attachment=') !== false) {
unset($rules[$rule]);
}
}
return $rules;
});
}, 1);
