[Resolved] Use different image for Featured Image in Header Element

Home Forums Support Use different image for Featured Image in Header Element

Viewing 6 posts - 1 through 6 (of 6 total)
  • Author
    Posts
  • #1396450
    Philip

    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.)

    #1397438
    Tom
    Lead Developer
    Lead Developer

    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 🙂

    #1397761
    Philip

    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.

    #1399172
    Tom
    Lead Developer
    Lead Developer

    Ah yea, sorry about that. Updated the function above to include the fallback 🙂

    #1399314
    Philip

    That did the trick, thanks!

    #1399700
    Tom
    Lead Developer
    Lead Developer
Viewing 6 posts - 1 through 6 (of 6 total)
  • You must be logged in to reply to this topic.