Support

Account

Home Forums Add-ons Flexible Content Field How to use an Image Field within Flexible Content to set the post's featured img

Solved

How to use an Image Field within Flexible Content to set the post's featured img

  • Within my Flexible Content, I’ve created a new layout with an Image field. I am trying to use it to update the post’s featured image. After multiple search attempts, the only thing I was able to find was this:

    function acf_set_featured_image( $value, $post_id, $field  ){
        
        if($value != ''){
    	    //Add the value which is the image ID to the _thumbnail_id meta data for the current post
    	    update_post_meta($post_id, '_thumbnail_id', $value);
        }
     
        return $value;
    }
    
    // acf/update_value/name={$field_name} - filter for a specific field based on it's name
    add_filter('acf/update_value/name=featimage', 'acf_set_featured_image', 10, 3);

    Now this code works perfectly with a stand-alone Image Field, but I can’t get it to work through an Image Field within Flexible Content. Can someone help me with this?

  • Hi @byoo

    Please keep in mind that the value of flexible content has a different structure. So it should be something like this:

    function my_acf_save_post( $post_id ) {
        
        // get the flexible content raw values
        $flexible_content = get_field('flexible_content_field_name', $post_id, false);
        
        // check if the post has flexible content or not
        if( $flexible_content ){
            
            // loop through the values
            foreach($flexible_content as $row){
                
                // check if the image is set in certain layout
                // please change 'layout_name' with your layout name and
                // 'field_1234567890abc' with the image field key
                if( $row['acf_fc_layout'] == 'layout_name' && isset($row['field_1234567890abc']) ){
                    
                    // update the featured image
                    update_post_meta($post_id, '_thumbnail_id', $row['field_1234567890abc']);
                }
            }
        }
    }
    
    // run after ACF saves the $_POST['acf'] data
    add_action('acf/save_post', 'my_acf_save_post', 20);

    Where “flexible_content_field_name” is the flexible content field name, “layout_name” is the layout name where the image field is located, and “field_1234567890abc” is the image field key.

    I hope this helps 🙂

  • Thank you so much!!

Viewing 3 posts - 1 through 3 (of 3 total)

The topic ‘How to use an Image Field within Flexible Content to set the post's featured img’ is closed to new replies.