Im trying to get this featured image only when wiewport is < 768:
add_image_size( 'img-movil', 660, false );
I have no much coding skills. I was reading about how to pass a variable from JS to PHP with jQuery $.ajax()
but I don’t understand it completely. This is what I did:
First step. I try to set JS variable and send it to the server:
$(document).ready(function(){
var viewportWidth = $(window).width();
if (viewportWidth < 768) {
var modoView = 'movil';
$.ajax({
type: "POST",
url: 'front-page.php',
data: {
modoView : modoView
},
success: function(data) {
alert("success!");
}
});
}
It doesn’t work (success allert doesn’t fire). I will appreciate any help with it.
Second step (when first step works), check if PHP variable is present (this code is in the body of front-page.php):
<?php
if (isset($_POST['modoView'])) {
$my_image_size="img-movil";
}
?>
Is it right?
Thank you in advance.
1 Answer
After a few days reading about srcset attribute (Thanks Benoti for point to this!), definitely, I can see that this is the right way. This solution is simple, enough to solve this question, although srcset
attribute with <picture>
tag is much more powerfull. My solution:
Declare sizes in functions.php
add_image_size( 'c200x200', 200, 200, true );
add_image_size( 'c400x400', 400, 400, true );
Check a custom field with the size stored
I have two types of posts, big and small, with 200×200 and 400×400 px img size.
$tamano = get_field('tamano');
if ($tamano == '200x200') {
$clase="c200x200";
} elseif ($tamano == '400x400') {
$clase="c400x400";
} else {
$clase="sin-clase";
}
Build the img tag
<?php
$img_id = get_post_thumbnail_id();
$img_src = wp_get_attachment_image_url( $img_id, 'c200x200' );
$img_srcset = wp_get_attachment_image_srcset( $img_id, $clase );
$alt_text = get_post_meta($img_id , '_wp_attachment_image_alt', true);
?>
<img
srcset="https://wordpress.stackexchange.com/<?php echo esc_attr( $img_srcset ); ?>"
alt="<?php echo $alt_text; ?>"
sizes="(min-width: 768px) 400px, 200px"
src="https://wordpress.stackexchange.com/questions/247897/<?php echo esc_url( $img_src ); ?>"
>
Background: