Site logo

Archived topic

Replace featured image single post (ACF)

5 replies · Started by Damiaan van Vliet on June 10, 2022

Viewing posts 1–6 of 6

Good morning great team,
I want to replace the featured image when displaying a single post with a image uploaded within a ACF field called "overview-picture".
I tried the code from this post (modified a bit), but it does not change a bit.

// replace featured image within a single post
add_filter( 'generate_featured_image_output', 'tu_custom_featured_image' );
function tu_custom_featured_image( $output ) {
    if ( get_post_meta( get_the_ID(), '_your_id', true ) ) {
        return '<img class="alignnone size-medium" src="[acf field=overview-picture]" alt="overview picture"/>';
    } else {
        return $output;
    }
}

Is the code still right?
To clarify, I want the use the original featured image in the blog overview.

Thank you for help.

Hi Damiaan,

That should work.

You would need to set the Return type of the field it Image URL. Then, set the src to that field.

For instance:

add_filter( 'generate_featured_image_output', 'tu_custom_featured_image' );
function tu_custom_featured_image( $output ) {
	$my_image = get_field('image_name');
    if ( $my_image ) {
        return '<img class="alignnone size-medium" src="' . $my_image .'" alt="overview picture"/>';
    } else {
        return $output;
    }
}

Replace image_name with the name of your field.

Hope this helps!

Thank you Fernando for the big help! It's almost right now.
With your adjusted code the featured image on the blog archive page is now changed to the "overview-picture".
And I wanted it the other way, I wanted the featured image on a single post to be changed. So that the featured image on a single post is replaced with the image "overview-picture"

So just the other way around so to speak :)

To clarify, are you wanting this to work for featured images for Single Posts?

If so, here’s another PHP snippet you may try:

add_filter( 'post_thumbnail_html', 'db_featured_image_before_after_content',10,5 );
 
function db_featured_image_before_after_content($html, $post_id, $post_thumbnail_id, $size, $attr) {
    if( ! is_single() || $html == '' ) { 
        
        return $html;
    
    } else {
		
	$my_image = get_field('image_name');
    if ( $my_image ) {
        $html = '<img class="alignnone size-medium" src="' . $my_image .'" alt="overview picture"/>';
    } 
        
    return $html;
    }

}

Kindly replace image_name with the field name of your image.

Hope this helps!

You're my hero Fernando! This is exactly what I wanted and the above code snippet I can use in another project.
Again thank you very much. :-)

You’re welcome Damiaan! Glad that worked! :)

This archived topic is closed to new replies.