Site logo

Archived topic

Set Post Thumbnail Via Elements

9 replies · Started by Tavis on January 31, 2020

Viewing posts 1–10 of 10

Hello,

I use custom fields and Elements to generate posts. I am hoping to use a custom field to also set the post thumbnail / featured image.

I feel like set_post_thumbnail() is the right direction, but I haven't been able to figure it out any further.

Any advice is appreciated!

Thanks,
TL

Hi there,

You can use a filter to do this:

add_filter( 'generate_page_hero_background_image_url', function( $url, $options ) {
    $custom_field = get_post_meta( get_the_ID(), 'your_custom_field', true );

    if ( $custom_field ) {
        $url = $custom_field;
    }

    return $url;
}, 10, 2 );

Let me know :)

Hi Tom,

Thanks for the quick reply!

Where is it best to put this code? In Elements or Code Snippets?

I am also using a custom post type if that makes a difference.

One more thing... I am using an Amazon plugin shortcode to get the image URL. The shortcode works for pulling the URL, but I am still not getting everything to work. Any advice?

add_filter( 'generate_page_hero_background_image_url', function( $url ) {
    $asin1 = get_field("asin1");
    $asin1_img_url = do_shortcode( '[amazon fields="' . $asin1 . '" value="image"]' );
    $custom_field = get_post_meta( get_the_ID(), $asin1_img_url, true );

    if ( $custom_field ) {
        $url = $custom_field;
    }

    return $url;
}, 10, 2 );

Code Snippets is the way to go for something like this.

Try this instead:

add_filter( 'generate_page_hero_background_image_url', function( $url ) {
    $asin1 = get_field("asin1");
    $asin1_img_url = do_shortcode( '[amazon fields="' . $asin1 . '" value="image"]' );

    if ( $asin1_img_url ) {
        $url = $asin1_img_url;
    }

    return $url;
}, 10, 2 );

Hmm still not working. I also tried it with a static URL and didn't work. Would it be possible for someone to go into my site and take a look?

Does the hero have a default background image set? If not, can you try setting a custom image as the background in the hero settings?

No there is no default background image set. I can set a custom image background in hero settings, but I don't see how this can allow me to dynamically set thumbnails to source external image URL via a custom field and short code.

Any other ideas?

Hi there,

I think what Tom meant was; try adding any Custom Image to the header element background.
Then test the function he provided. Let us know.

Ohhh, I see. Yes, that did work for the featured image. Does this method work for the post thumbnail image as well?

As long as a background image is set (featured image or custom image), the filter I shared should work.

Let me know :)

This archived topic is closed to new replies.