I'm making a Blogger theme and I'm trying to create a featured image for each post on the blogroll by grabbing the first image of each post and applying it as an element background image in each post. How can this be done?
So far I have gotten it to work somewhat, the problem is it applies the same image to every post, instead of each post. I tried putting it in a loop, but it didn't make a difference.
My code:
<b:loop values='data:post' var='this'>
<b:if cond='data:post.featuredImage'>
<a class='featured-image-link' expr:href='data:post.url'/>
<b:include data='{ image: data:post.featuredImage, selector: ".featured-image-link" }' name='responsiveImageStyle'/>
<else/>
<a class='featured-image-link' expr:href='data:post.url'/>
<style>background-image: url(https://1.bp.blogspot.com/-1AyCkdmJy98/Xa9kktaCsmI/AAAAAAAAfh0/zCRbtFo0di0iaU-eU5AWjx4Ndvt3sXmsgCLcBGAsYHQ/s1600/default-image-light_1920x1080.png);</style>
</b:if>
</b:loop>
Your loop won't work with this values
and var
, and you should write the selector before command for the alternative style, so you might try this one:
<b:loop values='data:posts' var='post'>
<a class='featured-image-link' expr:href='data:post.url'/>
<b:if cond='data:post.featuredImage'>
<b:include data='{ image: data:post.featuredImage, selector: ".featured-image-link" }' name='responsiveImageStyle'/>
<b:else/>
<b:include data='{ image: "https://1.bp.blogspot.com/-1AyCkdmJy98/Xa9kktaCsmI/AAAAAAAAfh0/zCRbtFo0di0iaU-eU5AWjx4Ndvt3sXmsgCLcBGAsYHQ/s1600/default-image-light_1920x1080.png", selector: ".featured-image-link" }' name='responsiveImageStyle'/>
</b:if>
</b:loop>
Edit :
I think you should use id
attribute instead of class
for your element, you can't use the same class for different generated styles, so depending on index of loop you can give each post a different id.
1- in the main loop of widget add attribute index='i'
, it should be similar to:
<b:loop values='data:posts' var='post' index='i'>
2- Put this block of code within the main loop of widget:
<a expr:id='("featured-image-link" + data:i)' expr:href='data:post.url'/>
<b:with value='data:post.featuredImage ?: "https://1.bp.blogspot.com/-1AyCkdmJy98/Xa9kktaCsmI/AAAAAAAAfh0/zCRbtFo0di0iaU-eU5AWjx4Ndvt3sXmsgCLcBGAsYHQ/s1600/default-image-light_1920x1080.png"' var='featuredImg'>
<b:include data='{ image: data:featuredImg, selector: ("#featured-image-link" + data:i) }' name='responsiveImageStyle'/>
</b:with>
Final code should be similar to:
<b:loop values='data:posts' var='post' index='i'>
<!-- your post elements -->
<a expr:id='("featured-image-link" + data:i)' expr:href='data:post.url'/>
<b:with value='data:post.featuredImage ?: "https://1.bp.blogspot.com/-1AyCkdmJy98/Xa9kktaCsmI/AAAAAAAAfh0/zCRbtFo0di0iaU-eU5AWjx4Ndvt3sXmsgCLcBGAsYHQ/s1600/default-image-light_1920x1080.png"' var='featuredImg'>
<b:include data='{ image: data:featuredImg, selector: ("#featured-image-link" + data:i) }' name='responsiveImageStyle'/>
</b:with>
<!-- your post elements -->
</b:loop>