How to Rewrite Image URL

This explains the system we use to display embedded images or thumbnails with remote urls in our apps.

It involves replacing references to the image urls with a local url which is of a form that we can intercept. Any requests for this url get processed by our code, at which point we extract the original url from the encoded url and redirect the request to the remote url. This means that the html included in the package only uses local urls and the images for those urls are also packaged.

We first declare an image constant at the top of your module, which will be used to build our local urls.

define( 'YOUREXTENSION_IMAGE_PREFIX', 'yourextension_images' );

We then replace remote urls with our customised local url.

 add_filter('the_content', 'yourextension_rewrite_images',10,2);
function yourextension_rewrite_images($content) {
  return pugpig_replace_image_urls($content, YOUREXTENSION_IMAGE_PREFIX);

At this point the html includes local image urls, but the images are still not in the package because they are not referenced in the manifest.

add_filter('yourextension_extra_manifest_items', 'yourextension_extra_manifest_items',10,2);
function yourextension_extra_manifest_items($output, $post) {
  $ret = $output;
  // Include the thumbnail image
  $thumbnail_image_url = yourextension_get_thumbnail_image($post);
  if ($thumbnail_image_url) {
    $ret .= "# Thumbnail image\n$thumbnail_image_url\n\n";
  // Include any images from the main body
  $ret .= pugpig_add_inline_images_to_manifest($post->post_content, YOUREXTENSION_IMAGE_PREFIX);
  return $ret;
function yourextension_get_thumbnail_image($post) {
  $article_thumbnail = get_post_meta($post->ID, "pugpig_thumbnail", true);
  if (strlen($article_thumbnail) > 0 && strlen(trim($article_thumbnail)) > 0){
    $path_parts = pathinfo($article_thumbnail);
    $extension = $path_parts['extension'];
    if ($extension == "jpeg" || $extension == "jpg" || $extension == "png" || $extension == "gif") {
      return pugpig_get_encoded_image_url(trim($article_thumbnail), YOUREXTENSION_IMAGE_PREFIX, false);
  return "";

Finally, we need to add something to handle the manifest's request.

add_action('template_redirect', 'yourextension_catch_request');
function yourextension_catch_request() {

Was this article helpful?
0 out of 0 found this helpful
Have more questions? Submit a request


Powered by Zendesk