Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you display different Featured Image with different sizes when using Media Queries

Since featured image sets default sizes, example:

add_image_size( 'post-thumbnails2200px', 360, 250, true );
add_image_size( 'post-thumbnails1280px', 250, 250, true );
add_image_size( 'post-thumbnails800px', 150, 250, true );

my question is how do you display featured image with different sizes without using the css max-width or any css styles.

I'm having trouble displaying it when i try on different resolution. actually, i have no idea what to do. when i use css, it gets distorted since the height is fixed in 250px.

i am wondering if you someone could share their php if and else script or javascript or anything. please help!

like image 314
Ben Daggers Avatar asked Jan 24 '26 03:01

Ben Daggers


1 Answers

With just Javascript and PHP:

PHP

You can get the various image sizes using the_post_thumbnail() as per the codex:

the_post_thumbnail();                  // without parameter -> 'post-thumbnail'

the_post_thumbnail('thumbnail');       // Thumbnail (default 150px x 150px max)
the_post_thumbnail('medium');          // Medium resolution (default 300px x 300px max)
the_post_thumbnail('large');           // Large resolution (default 640px x 640px max)
the_post_thumbnail('full');            // Full resolution (original size uploaded)

the_post_thumbnail( array(100,100) );  // Other resolutions

Javascript

You can get the widow size as described here using jQuery(window).width().

By combining the two, you could do something like the following in your theme's template files, inside the loop:

<script>
    if( jQuery(window).width() < 480 ) {
        <?php the_post_thumbnail('medium'); ?>
    }
    else if( jQuery(window).width() < 960 ) {
        <?php the_post_thumbnail('large'); ?>
    }
    else {
        <?php the_post_thumbnail('full'); ?>
    }
</script>

Caveat: I don't have a machine to test this on right now, but if the above doesn't work, try replacing <?php the_post_thumbnail('medium'); ?> with image = <?php get_the_post_thumbnail($post_id, 'medium'); ?>; etc. (see info about get_the_post_thumbnail() here).

<?php $post_id = get_the_ID(); ?>

<div id=my-div></div>

<script>
    if( jQuery(window).width() < 480 ) {
        var image = <?php get_the_post_thumbnail($post_id, 'medium'); ?>;
    }
    else if( jQuery(window).width() < 960 ) {
        var image = <?php get_the_post_thumbnail($post_id, 'large'); ?>;
    }
    else {
        var image = <?php get_the_post_thumbnail($post_id, 'full'); ?>;
    }

    jQuery('#my-div').append(image);
</script>
like image 154
apostl3pol Avatar answered Jan 26 '26 18:01

apostl3pol



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!