Disable WordPress Recognizing Path as Attachment

After getting to know a bit more about the default perma structure and how to modify it I stumbled upon the hook rewrite_rules_array. This hook allows you to filter the array of rewrite rules, an array of URL rewrite rules in WordPress what will help determine what type of content to load.

This is a great place to disable the default behavior for recognizing the path as attachment. This is how you get rid of all rewrite rules for attachments, thus all the behavior for recognizing a path as attachment.

add_filter('rewrite_rules_array', function($rules) {
    foreach ($rules as $rule => $url) {
        if (strpos($url, 'attachment') !== false) {
            unset($rules[$rule]);
        }
    }
    return $rules;
});

I’m not sure about all other rules and I definitely want to check them all out. These for example:

"(.?.+?)(?:/([0-9]+))?/?$" => "index.php?pagename=$matches[1]&page=$matches[2]"
"([^/]+)(?:/([0-9]+))?/?$" => "index.php?name=$matches[1]&page=$matches[2]"

Will help you recognize pages, very useful to know if you only want to use pages. But remember if you rewrite the array with only these keys/values then new rules for example rules for your custom post type will also be rewritten (removed).

NOTE: Debugging this filter is only possible on the Settings > Permalinks page in the WordPress back-end.

Leave a Comment