Delicious Brains

Documentation

Filtering URLs in Custom Content

Since WP Offload S3 1.2, URLs within post content have been rewritten on page generation. This includes posts, pages, and custom post types. WP Offload S3 does this by hooking into the_content filter and automatically converting local Media Library URLs to their S3 counterpart.

If you’re directly querying the wp_posts table or storing custom content in a different table you may need to manually apply the_content to ensure that Media Library URLs are rewritten. However, there may be times when the_content isn’t appropriate due to the other filters that are applied. For example, you may not want shortcodes to be parsed or paragraph tags inserted. WP Offload S3 exposes two filters for this scenario.

Converting Local to S3

The as3cf_filter_post_local_to_s3 filter can be used to rewrite any local Media Library URLs to S3. Ideally, this filter should be applied anytime that you’re retrieving information from the database. You do not need to call this filter if it’s already being passed through the_content.

$content = 'Lorem ipsum... <img src="http://wordpress.dev/wp-content/uploads/2017/03/image.jpeg" alt="" width="300" height="200" class="alignnone size-medium wp-image-491" />';
$content = apply_filters( 'as3cf_filter_post_local_to_s3', $content );
// $content = 'Lorem ipsum... <img src="https://s3-eu-west-1.amazonaws.com/your-bucket-name/wp-content/uploads/2017/03/image.jpeg" alt="" width="300" height="200" class="alignnone size-medium wp-image-491" />';

Converting S3 to Local

The as3cf_filter_post_s3_to_local filter will rewrite any S3 URLs to the local server. It’s best practice to apply this filter before saving any custom content to the database. This will ensure only local URLs exist in the database.

$content = 'Lorem ipsum... <img src="https://s3-eu-west-1.amazonaws.com/your-bucket-name/wp-content/uploads/2017/03/image.jpeg" alt="" width="300" height="200" class="alignnone size-medium wp-image-491" />';
$content = apply_filters( 'as3cf_filter_post_s3_to_local', $content );
// $content = 'Lorem ipsum... <img src="http://wordpress.dev/wp-content/uploads/2017/03/image.jpeg" alt="" width="300" height="200" class="alignnone size-medium wp-image-491" />';