Delicious Brains

Documentation

Assets: Getting the URL of an asset

The Assets addon for WP Offload S3 intelligently scans WordPress core, your theme, and your plugin folders for assets, uploads them to S3, and rewrites URLs so they are served from S3, CloudFront, or another CDN according to your settings. However, it only rewrites assets that make use of WordPress’ enqueue system. Any assets linked to directly in your theme are not rewritten. A very common example of this is the favicon. You might have something like the following in your theme:

<link rel="apple-touch-icon"
    href="<?php echo get_template_directory_uri(); ?>/assets/img/apple-touch-icon.png">

We need to modify this to allow WP Offload S3 to replace the local server URL with the Amazon S3/CloudFront URL.

<link rel="apple-touch-icon" 
    href="<?php echo apply_filters( 'as3cf_get_asset', get_template_directory_uri() . '/assets/img/apple-touch-icon.png' ); ?>">

Now we pass the entire local server URL to the as3cf_get_asset filter and that filter will check if we’ve uploaded the file to S3 and return the S3/CloudFront URL if so.

You may be wondering why we didn’t just create a as3cf_get_asset( $asset_url ) function. If we went this route you would get a “function does not exist” error or a white screen when WP Offload S3 or the Assets addon are deactivated. With a filter, the local server URL will be used if our plugins are deactivated and the filter doesn’t exist.

You may also be wondering why we don’t just do output buffering and run a find & replace on the whole page content just before output. This would slow things down quite a bit in environments where there is no full-page caching. It could also lead to side effects like breaking third-party plugins. We decided it would be safer to have developers implement the filter instead.