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:
https://make.wordpress.org/core/2015/11/10/responsive-images-in-wordpress-4-4/