Site icon DopeThemes

WordPress Remove CDN Version from URL

WordPress Remove CDN Version from URL

When using a CDN (Content Delivery Network) to serve your assets like JavaScript and CSS files, having version numbers (query strings) appended to the file URLs can sometimes cause loading issues. This is especially true for CDNs that do not cache URLs with query strings effectively. Removing the file version from CDN URLs can resolve these issues and improve performance. Below is a simple solution to help you remove the file version from CDN URLs in WordPress.

Removing File Version from CDN URLs

To remove the version query string from assets served via your CDN, you can use a custom function hooked to the script_loader_src filter. The following code snippet demonstrates how to do this:

/**
 * Remove the file version query string from CDN URLs.
 *
 * This function removes the 'ver' query string from any asset URL
 * that is served from a specific CDN. This is useful when the CDN
 * has issues loading files with version numbers.
 *
 * @param string $src The original asset URL.
 * @return string The asset URL without the version query string.
 */
function theme_name_cdn_version_remove( $src ) {

    // Check if the URL contains the CDN domain
    if ( strpos( $src, 'cdn_name_here.com' ) ) {
        // Remove the version query string ('ver') from the URL
        $src = remove_query_arg( 'ver', $src );
    }

    return $src;
}

// Apply the filter to remove the version query string from script URLs
add_filter( 'script_loader_src', 'theme_name_cdn_version_remove', 9999 );

How It Works

Additional Option: Apply to Both JavaScript and CSS

If you also want to remove the version string from your CSS files served by the CDN, you can apply the same logic to the style_loader_src filter like this:

add_filter( 'style_loader_src', 'theme_name_cdn_version_remove', 9999 );
Conclusion

By using this simple code, you can ensure that version numbers are removed from your CDN URLs, helping to resolve loading issues and improving the performance of your site. Simply add this code to your theme’s functions.php file or a custom plugin, and replace cdn_name_here.com with the actual CDN domain you’re using. This will ensure that your assets are loaded correctly without unnecessary query strings.

Next: WooCommerce vs Shopify

Exit mobile version