1

There was an older question that I answer where someone wanted to remove the HTTP and HTTPS protocols from the URLs on their website:

add_action( 'plugins_loaded', 'output_buffering' );

function output_buffering() {
    ob_start( 'remove_protocols' ) );
}

function remove_protocols( $buffer ) {
    $content_type = NULL;
    foreach ( headers_list() as $header ) {
        if (strpos( strtolower( $header ), 'content-type:' ) === 0 ) {
            $pieces = explode( ':', strtolower( $header ) );
            $content_type = trim( $pieces[1] );
            break;
        }
    }
    if ( is_null( $content_type ) || substr( $content_type, 0, 9 ) === 'text/html' ) {
        $return = preg_replace( '~=\s*["\']\s*https?:(.*?)["\']~i', '="$1"', $buffer );
        if ( $return ) {
            $buffer = $return;
        }
    }
    return $buffer;
}

As a result, it gives the following:

<link rel='stylesheet' id='some-id'  href='//example.com/some/style.css' type='text/css' media='all' />
<script type='text/javascript' src='//example.com/some/script.js'></script>
<a href="//example.com" title="Some Title" rel="home">Some Link</a>
<img src="//example.com/some/image.jpg" alt="Some Alt" width="150" height="50" />

However, I've simplified the remove_protocols() function which gives me the same results:

function remove_protocols( $buffer ) {
    $buffer = preg_replace( '~=\s*["\']\s*https?:(.*?)["\']~i', '="$1"', $buffer );
    return $buffer;
}

In my original function, is it necessary to check for content-type in headers? Doing some research, I found a similar question on Stack Overflow which is depends on the situation. From reading this, I assume that it would be safe to use my simplified version instead, but I would like to get a confirmation if I am understanding this correctly.

1 Answer 1

1

In the context of that question, yes it is. Without inspecting the content type header you don't know if what is being served is an html page or an image, and while it is unlikely that the regex will match anything in an image, the risk is there.

a different way to write that code is to hook it on template_redirect or even get_header to be as close to 100% sure you are dealing with html pages and not RSS, json, xml etc, for which that URL transformation might not be required or even welcome.

looking again at the original question, obviously you will want it in the admin pages as well... so maybe your original solution is the most comprehensive that can actually be.

OTOH, and not very related to this question, you might end with replacing too much, like the canonical url which might create duplicate content problem.

2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.