Archived topic
Use different image for Featured Image in Header Element
5 replies · Started by Philip on August 10, 2020
I'm currently using {{custom_field._thumbnail_id}} to display each post's Featured Image in the Header Element, which works great.
However, sometimes, I need to use a different image than the Featured Image for the Header. I'm thinking I could use ACF to add an image field for this, but then I'm unsure how to provide that image to the Header Element.
I found this post which seems pretty close to what I want, but I don't want to use a background image: https://generatepress.com/forums/topic/page-hero-custom-background-image-from-custom-field-with-fallback/#post-1164776
I need to have it actually be an tag, which I can do using
{{custom_field._thumbnail_id}}.
Is there a way to do what I'm trying? Maybe some filter like generate_hero_thumbnail_image_url?
(I also realize I could accomplish this by making a different Header Element for every post, but that is not feasible due to the planned number of posts.)
Hi there,
You could build a shortcode:
add_shortcode( 'custom_image', function() {
$image_url = get_post_meta( get_the_ID(), 'your_custom_field_name', true );
if ( $image_url) {
return '<img src="' . $image_url . '" />';
} elseif ( has_post_thumbnail() ) {
return get_the_post_thumbnail();
}
} );
Then you could use [custom_image] in the Element.
Let me know :)
Hi Tom,
Thank you, I think this has got me on the right track.
When you put if ( $custom_field ) {, did you actually mean if ( $image_url ) {, because it didn't work for me until I changed that.
Then my only other issue is that if there is no custom_image set in the ACF field, then it's not using the featured image by default - its just not returning anything. Any way to make it do that?
Thank you.
Ah yea, sorry about that. Updated the function above to include the fallback :)
That did the trick, thanks!
You're welcome :)