Filtering URLs in Custom Content
Since WP Offload Media 1.2, URLs within post content have been rewritten on page generation. This includes posts, pages, and custom post types. WP Offload Media does this by hooking into the_content
filter and automatically converting local Media Library URLs to their cloud storage 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 Media exposes two filters for this scenario.
Converting Local to Cloud Storage
The as3cf_filter_post_local_to_provider
filter can be used to rewrite any local Media Library URLs to their cloud storage version. 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_provider', $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 Cloud Storage to Local
The as3cf_filter_post_provider_to_local
filter will rewrite any cloud storage 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_provider_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" />';
Backwards Compatibility
Prior to WP Offload Media v2.0 the filters were named as3cf_filter_post_local_to_s3
and as3cf_filter_post_s3_to_local
, and still work in the current version to maintain backwards compatibility.