Support

Account

Home Forums General Issues Unattached image still shows as attached Reply To: Unattached image still shows as attached

  • I managed to work it out, so am posting it here in case anyone else comes looking for it 🙂

    Points to note:
    – Thinking that it may help someone else, I’ve left a few debugging lines in the below code
    – I am also setting the first entry in the gallery array as the Featured Image / Thumbnail because it isn’t an option I am making available to the users of my site.

    add_action('acf/save_post', 'manage_portfolio_media', 1);
    function manage_portfolio_media($post_id) {
    	
        if ( get_post_type($post_id) == 'ocean_portfolio' ){
    	
            $acf = false;
            if( isset($_POST['acf']) ) {
                $acf = $_POST['acf'];
            }
    
            $field_key = 'field_5e92f3aacc8a6';
            $field_name = 'attachments';
            
            if (isset($acf[$field_key])) {
                $previous_images = get_field($field_name, $post_id);
                $new_images = $acf[$field_key];
    
    			// create a lookup of ids for images in the post
                $new_lookup = array();
                if (!empty($new_images)) {
                    foreach($new_images as $imageid) {
                        array_push($new_lookup, $imageid);
                    }
                }
    
                // create a lookup of images that were removed
                $removed_lookup = array();
                if (!empty($previous_images)) {
                    foreach($previous_images as $image) {
    					error_log('Previous Array = ' . $image['ID']);
                        if (!in_array($image['ID'], $new_lookup)) {
                            array_push($removed_lookup, $image['ID']);
                        }
                    }
                }
    
                if (!empty($removed_lookup)) {
                    foreach($removed_lookup as $imageid) {
                        // unattach removed ones
    					error_log('Removed Item = ' . $imageid);
    					wp_update_post( array( 'ID' => $imageid, 'post_parent' => 0 ) );
                    }
                }
    
                if (!empty($new_lookup)) {
    				set_post_thumbnail( $post_id, $new_lookup['0'] );
    				error_log('New Thumbnail = ' . $new_lookup['0']);
                    foreach($new_lookup as $imageid) {
                        // attach added ones
    					error_log('New Array = ' . $imageid);
    					wp_update_post( array( 'ID' => $imageid, 'post_parent' => $post_id ) );
                    }
                }
            }
        }
    }