Show theme images based on the visitor's browser

Hello everyone,

I’m trying to get my WordPress site to display theme images in the appropriate format based on the visitor’s browser and its supported image types, such as WebP, GIF, JPEG, etc.

So far, I’ve tried adding this code to the end of the functions.php file in my theme:

// Añade soporte para el formato de imagen WebP (no es necesario si usas WordPress 5.8 o superior)
/*
function add_webp_mime_type( $mimes ) {
  $mimes['webp'] = 'image/webp';
  return $mimes;
}
add_filter( 'mime_types', 'add_webp_mime_type' );
*/

// Muestra las imágenes del tema activo en la misma carpeta que la imagen sidebar-bg.jpg
function show_theme_images() {
  // Obtiene la URL de la carpeta de imágenes del tema activo
  $theme_directory = get_template_directory_uri() . '/wp-content/';

  // Define los formatos de imagen permitidos
  $image_formats = array( 'webp', 'jpeg', 'jpg', 'png', 'gif' );

  // Obtiene la ruta física de la carpeta de imágenes del tema activo
  $image_path = get_template_directory() . '/wp-content/';

  // Obtiene todas las imágenes válidas en la carpeta de imágenes del tema activo
  $images = get_images_in_directory( $image_path, $image_formats );

  if ( $images ) {
    foreach ( $images as $image ) {
      // Obtiene la URL y la ruta física de la imagen actual
      $image_url = $theme_directory . $image;
      $image_file = $image_path . $image;

      // Obtiene el tipo MIME de la imagen actual
      $mime_type = wp_check_filetype( $image_file )['type'];

      // Si el navegador admite el tipo MIME de la imagen actual, la muestra y sale del script
      if ( in_array( $mime_type, $image_formats ) ) {
        header( "Content-type: $mime_type" );
        readfile( $image_url );
        exit;
      }
    }
  }
}

// Obtiene todas las imágenes válidas en una carpeta dada
function get_images_in_directory( $directory, $formats ) {
  $images = array();

  if ( is_dir( $directory ) ) {
    $files = scandir( $directory );

    foreach ( $files as $file ) {
      $path = $directory . $file;
      $extension = strtolower( pathinfo( $path, PATHINFO_EXTENSION ) );

      if ( in_array( $extension, $formats ) ) {
        $images[] = $file;
      }
    }
  }

  return $images;
}

// Agrega el script que muestra las imágenes del tema activo al inicio de la ejecución de WordPress
add_action( 'init', 'show_theme_images' );

And I’ve uploaded WebP versions of the images with the same name to the theme folder where the original versions are located.

However, I haven’t been able to achieve any results, and I can’t figure out why. I even tried changing the image folder path to be less specific, in case that was the issue. Could someone please help me out?

Can you be more specific? What does it do that it shouldnt do, or what does it not do that it should?

Thank you for your reply. The issue is that the code doesn’t seem to be displaying the images in the proper format according to the browser that’s visiting the site and what it supports. I’ve tried adding the code to the end of the theme’s functions.php file, and I’ve uploaded WebP versions of the images with the same name to the theme folder where the original versions are located. However, it doesn’t seem to be working and I’m not sure why. I’ve also tried changing the image folder path to make it less specific, but it didn’t help. Do you have any suggestions on how to make it work properly?

Well nothing in your current code is related to the browser in any way.

You define a static list of 5 formats, then get the images in that directory that match your formats.

Could you help me find a solution that allows me to do what I’m looking for? The theme I’m using uses GIF and JPEG images for the background, sidebars, etc. My intention is that any browser that supports WebP will see the versions in this format that I have uploaded to the theme’s image folder instead of the original ones, so that the loading speed is faster, while those that are not compatible continue to see the original formats.

Are you sure what you’re trying to do is… yaknow… applicable?

Every modern browser (Read: Everything except the discontinued and removed-from-service Internet Explorer) support webp, jpeg, jpg, png, and gif. Are there more esoteric image formats you’re trying to support?

I want to implement that function for visitors who are using outdated browsers that do not yet support WebP, as well as for unknown and unusual browsers that also do not support it.

So to be clear… you’re looking to implement some sort of code that caters specifically to those who havent updated their browser in more than 5 years, and which accounts for a total of less than 2% of the world’s users as detected by caniuse.

I see.

I’m going to be upfront and honest and say I’m not aware of any premade code that would handle this scenario; probably because of the above statement about percentage of users. You could try to sniff a useragent, but you’d have to know what you were looking for (like… you could look for Chrome version 4, 5, 6, 7, and 8, then repeat for firefox version 2, 3, 4, 5…63, and 64, but… are you really going to?)

As m_hutley says, it’s going to be a huge project sniffing the user agent string of all the browsers and figuring out which don’t support webp. Then on top of that you figure that users can change user agent strings, and your “unknown and unusual browsers” will likely have a random user agent string that you can’t tell whether it is a good or bad one.

If supporting these folks is that important, I would just skip using webp format. Those browsers are likely to also not support many of the newer CSS and HTML tags as well, by the way.

I have been working with ChatGPT and he has proposed a new code, but when I paste it into functions.php, the website screen goes blank, so I have to revert the changes.

In principle, it seems that it should be possible to detect if the browser is compatible, instead of what kind of browser it is, and if so, that would be enough to apply the changes to the page. However, my programming skills are limited, which is why I’m asking for help. It may apply to a low percentage of my visitors, but I like to cover all possibilities.

Ah, you like to cover ALL possibilities?

Cool. Never use webp.
Also, you cant use CSS, because that wasnt supported in all browsers ever.
Oh and Javascript functions. Yeah, those weren’t available in Android browsers until 2013. So, throw all those away. Along with… yaknow… Wordpress.
Obviously, cant use HTML5 in any way… probably not HTML4, to be on the safe side…

Careful when you say you want to cover all possibilities :slight_smile:

@m_hutley Do you know the use of Reductio ad absurdum or Appeal to Extremes?

I do. But do you know the use of Defining Requirements?

Are you going to specify that we’re ONLY talking about webp now? You were talking about images. What about TIFF? (throw out anything but Safari) SVG? (Most IE, early versions of Safari and Firefox go on the list to throw out) What about inline SVG? (throw in a few versions of Opera and Chrome)…

Is it so absurd now?

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.