0

How to Serve Static Assets in WordPress Admin From W3TC CDN

Posted (Updated ) in PHP

With the rise of Gutenberg and it’s million tiny JavaScript files loaded every time you go to write a post, it’s become more important than ever to utilise a CDN for static assets loaded through the WordPress admin.

W3 Total Cache is a great plugin for speeding up your site and it’s CDN feature is top notch. One seemingly missing feature however is serving static assets from the configured CDN when browsing around your sites admin. By default no CDN rewriting at all is done on your sites backend and if you have a lot of logged in users writing posts, this can cause a bunch of unnecessary load on your server as they each download all the files.

Luckily this feature is pretty simple to add yourself with the following code block:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
// Automatically rewrite assets to CDN URLs in the backend
if (class_exists('W3TC\Dispatcher')) {
    add_action('admin_init', function () {
        $config = new W3TC\Config();
 
        if ($config->get('cdn.enabled')) {
            // CDN domain with trailing slash
            $cdn_domain = W3TC\Dispatcher::component('Cdn_Core')->get_cdn()->format_url('');
 
            /**
             * Filters the HTML link tag of an enqueued style.
             *
             * @since 2.6.0
             * @since 4.3.0 Introduced the `$href` parameter.
             * @since 4.5.0 Introduced the `$media` parameter.
             *
             * @param string $html   The link tag for the enqueued style.
             * @param string $handle The style's registered handle.
             * @param string $href   The stylesheet's source URL.
             * @param string $media  The stylesheet's media attribute.
             */
            add_filter('style_loader_tag', function ($tag, $handle, $href, $media) use ($cdn_domain) {
                return str_replace(site_url('/'), $cdn_domain, $tag);
            }, 10, 4);
 
            /**
             * Filters the HTML script tag of an enqueued script.
             *
             * @since 4.1.0
             *
             * @param string $tag    The script tag for the enqueued script.
             * @param string $handle The script's registered handle.
             * @param string $src    The script's source URL.
             */
            add_filter('script_loader_tag', function ($tag, $handle, $src) use ($cdn_domain) {
                return str_replace(site_url('/'), $cdn_domain, $tag);
            }, 10, 3);
        }
    });
}

I’d only recommend using this code with an Origin Pull CDN, as it doesn’t handle pushing any of these assets to the CDN – only serving from what’s already in there (which if using an Origin Pull CDN will be everything).