Support » Fixing WordPress » How to modify all href and src links?

Viewing 5 replies - 1 through 5 (of 5 total)
  • You could just do a redirect, like this:

    function my_custom_redirect() {
        if ( is_page( 'test' ) ) {
            global $wp;
            $current_url = add_query_arg( $wp->query_string, '', home_url( $wp->request ) );
            $new_url = str_replace( 'example.com', 'test.example.com', $current_url );
            header( "Location: {$new_url}" );
            exit;
        }
    }
    add_action( 'wp', 'my_custom_redirect' );

    In this example, the conditional tag checks if the current page is a page with a slug of test and, if true, replaces example.com with test.example.com and redirects.

    Would that work in your case? It would certainly be more efficient than doing a preg_replace and changing all href and src attributes…

    CREDIT: The method for retrieving the current URL was shamelessly yoinked from this blog post by Konstantin Kovshenin.

    Thanks for the response.

    If I got this right, it would only work if the url is something like http://example.com/test or http://example.com/user/test/ ? And if that’s the case, I am afraid it wouldn’t work for me.

    So if you could help me with the preg_replace method, I’ll be greatful.

    The method above could work in any case where the URL you want and the current URL are identical, except for the sub-domain. You would just need to change the conditional tag in the if statement.

    There really isn’t an easy or good way to preg_replace every href and src value. You’d have to write a function to change all of the enqueued script and style URLs; another to filter the content; and possibly several others. It would be a total hack.

    Here is an alternative version of that function, which uses wp_redirect:

    function my_custom_redirect() {
        if ( is_page( 'test' ) ) {
            global $wp;
            $current_url = add_query_arg( $wp->query_string, '', home_url( $wp->request ) );
            wp_redirect( preg_replace( 'example.com', 'test.example.com', $current_url ), 301 );
            exit;
        }
    }
    add_action( 'wp', 'my_custom_redirect' );

    Hey, I was away. I just looked at your last response. This should do what I want. I’ll give it a go today. Thanks again!

Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘How to modify all href and src links?’ is closed to new replies.