Show theme images based on the visitor’s browser

The code you’ve provided seems to have a few issues that might be causing the problem. Here’s my suggestions:

  1. In WordPress, your theme’s images should typically be stored in a directory within your theme’s folder, not in /wp-content/. The /wp-content/ directory is generally where themes, plugins, and uploads are stored, not individual images for a specific theme. You may want to create a subdirectory in your theme’s directory, such as /images/, and store your images there. You would then adjust your **$theme_directory** and **$image_path** variables to reflect this.

  2. Your $image_formats array seems to be holding file extensions, not MIME types. However, in your show_theme_images() function, you’re using it to check against the MIME type of the image. You should either rename this variable to $file_extensions and adjust your code accordingly, or change its values to the corresponding MIME types (e.g., ‘image/webp’, ‘image/jpeg’, ‘image/jpg’, ‘image/png’, ‘image/gif’).

  3. Your show_theme_images() function is designed to send headers, which can cause issues if it’s hooked into the ‘init’ action, because WordPress may have already started outputting the page by this point. This would result in a “headers already sent” error. A different approach is necessary to output images based on browser capabilities.

A better approach may be to use the <picture> element in your theme’s templates, which allows you to specify multiple sources for an image and lets the browser choose the most suitable one. Here’s an example:

<picture>
  <source srcset="<?php echo get_template_directory_uri(); ?>/images/your-image.webp" type="image/webp">
  <source srcset="<?php echo get_template_directory_uri(); ?>/images/your-image.jpg" type="image/jpeg"> 
  <img src="<?php echo get_template_directory_uri(); ?>/images/your-image.jpg" alt="Alt Text">
</picture>

In this code, the browser will try to use the WebP image first. If it can’t (because it doesn’t support WebP images, for example), it’ll fall back to the JPEG image. The tag is used as a final fallback for browsers that don’t support the element.

Please ensure that you replace ‘your-image.webp’ and ‘your-image.jpg’ with the correct image file names. The get_template_directory_uri() function returns the URL of the current theme, so you should place your images in the root of your theme directory (or adjust the path in the srcset attributes if you’re using a subdirectory for your images).

Please note that it’s crucial to keep all images optimized and to use a caching plugin to serve static images to speed up your WordPress site. Also, if your website is behind a CDN, ensure that the CDN supports these image formats.