简体   繁体   中英

Detect screen width to render appropriate images for breakpoints

So I know it's not possible to grab the screen width using PHP, but I wanted to see what would be the cleanest way that I can "Check breakpoints" and then pass in the appropriate call?

So I have this function:

function get_featured_image($post_id) {
    $thumbnail = get_field('featured_image_mobile', $post_id);
    if (strstr(strtolower($_SERVER['HTTP_USER_AGENT']), 'mobile') || strstr(strtolower($_SERVER['HTTP_USER_AGENT']), 'android') && ($thumbnail)) {
        echo '<img src="' . $thumbnail['sizes']['medium'] . '" alt="" class="imagery featured-image-selection"/>';
    } else if (has_post_thumbnail($post_id)) {
        echo '<img src="' . get_the_post_thumbnail_url() . '" alt="" class="imagery featured-image-selection"/>';
    }
}

I'm checking the user_agent on whether it's mobile or not and outputting a img src using ACF, otherwise if it's desktop and has the thumbnail, use that, but it's not the most reliable in determining sizing since the mobile view on desktop comes back as "desktop" still.

Is there a cleaned way that I can detect "breakpoints" so that I can use the $thumbnail['sizes']['medium'] up until like 700px and then use get_post_thumbnail_url() with anything above 700px in width?

I don't know if your goal is to use just PHP but the easiest way is to use CSS. These are basic media queries, you can change them as you want.

// For small devices
@media (min-width: 576px) {
    .imagery {
        background-image: url("images/thumbnail-small.jpg");
    }
}
// For medium devices
@media (min-width: 768px) {
    .imagery {
        background-image: url("images/thumbnail-medium.jpg");
    }
}
// For large devices
@media (min-width: 992px) {
    .imagery {
        background-image: url("images/thumbnail-large.jpg");
    }
}
// For larger devices
@media (min-width: 1200px) {
    .imagery {
        background-image: url("images/thumbnail-larger.jpg");
    }
}

I got a reference from Bootstrap's page but there are lots of pages and examples.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM