Web Development & WordPress

WordPress Shortcode to Show Different Images for Desktop & Mobile

Basically client was asking to show different image in desktop view and mobile view. So the idea which hits in my mind to create a shortcode which will check if client is visiting the site from mobile or from desktop/laptop and return the image based on it

So the shortcode need to be used in the following way, put it in the img html tag where u want to show the different image

<img src="[responsive_image]" alt="" title="" /> 

Here is the code which will go in the function.php portion

function responsive_image_shortcode() {
    // Check if the user is on a mobile device
    $is_mobile = wp_is_mobile();
    
    // Set the appropriate image URL based on device
    if ($is_mobile) {
        $image_url = 'MOBILE IMAGE URL';
    } else {
        $image_url = 'DESKTOP IMAGE URL';
    }
    
    // Return the image URL
    return $image_url;
}
add_shortcode('responsive_image', 'responsive_image_shortcode');

Leave a comment