Reputation: 6054
First of all: is it even possible?
I'd like to get a function that returns an srcset <img>
tag to make my wordpress layout responsive. This is important for me because my wrapper is 1400 wide, which is good for screens wider than 1400 @1 or 700 @2, but for mobile phones is too wide, and 720px width would be enough for @2 and even @3 screens (as they could get sharper but eye wouldn't notice too much).
The problem is I can't know which thumbnail size to serve while processing the php... so I'd like to use a srcset
. To do that I know I must write something on the functions.php
. But what should I do and how? Should I modify the_post_thumbnail()
function? Or should I create a new one? In that case, how can I get the different image names from the different sizes of the post thumbnail?
Upvotes: 0
Views: 2652
Reputation: 1759
You can use wp wp_get_attachment_image_src()
and get_post_thumbnail_id()
functions to create yourself the <img>
tag:
global $post;
$url1 = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'thumbnail' );
$url2 = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'medium');
<img src="<?php echo $url1[0]; ?>" srcset="<?php echo $url2[0]; ?> 500w" alt="alt-text" />
Where "thumbnail" and "medium" are the image sizes name. For example, the default WordPress sizes are thumbnail, medium, large and full. Your theme can have more sizes declared.
If you are inside the loop you don't need to declare de global $post
.
Upvotes: 0
Reputation: 386
You can use filter to modify the_post_thumbnail function.
use the below filter to modify the output generated by the_post_thumbnail function.
add_filter( 'post_thumbnail_html', 'your_function', 10, 6 );
Upvotes: 1