WordPress use CDN with out plugin

Content Devlivery Network (CDN) allow your web site to serve images from another domain or a sub domain. This speed up web site as your web server don’t need to serve images. Also browsers have a limit on number of parallel downloads from same domain. Having images on a differnt domain bypass this limitation of web browser.

If you use a pull type CDN or a CDN that you manually upload using some sync tool, you need to rewrite all image url to CDN url. There are several plugins available to do this. But you can easily do this with out any plugins.

Edit file

wp-content/themes/YOUR-THEME/functions.php

Add following code to end of the file.

add_filter('wp_get_attachment_image_src', 'staticize_attachment_src', null, 4);

function staticize_attachment_src($image, $attachment_id, $size, $icon) {
    if (is_array($image) && !empty($image[0])) {
        $image[0] = str_replace( 'https://www.YOUR-DOMAIN-HERE/wp-content/uploads/', 'https://cdn.YOUR-DOMAIN-HERE/wp-content/uploads/', $image[0] );
    }
    return $image;
}

This will replace image urls with CDN url.

Need help with Linux Server or WordPress? We can help!

Leave a Reply

Your email address will not be published. Required fields are marked *