Delete Post but retain image of post [WP REST API]

Currently, when I delete a post in my wordpress website, the image is deleted automatically.

Which is fine for most cases, however, there are certain posts where I don't want to delete the image from the database such as a post that has the plain website logo (default background image when subscribers don't post image). In such case, how can I delete the post while keeping the image.

I'am using the wordpress rest api and issuing the following request (in python) to delete the post.

url='https://mywebsite.com/wp-json/wp/v2/posts'
post_id=22334

r = requests.delete(url + '/' + str(post_id) + '?force=True')

Any suggestions?

Possible solution routes:

-Is there a way to mark/protect an image from auto deletion when post is deleted

-Is there a way to instruct wordpress not to delete featured media when deleting the post

This is the deleteimage function used by the custom theme when a post is deleted:

public function deleteImages(Post $post)
{
    foreach (themeApp('gallery_fields') as $galleryField) {
        /* @var GalleryField $galleryField */
        foreach ($galleryField-getValue($post) as $imageId) {

            wp_delete_attachment($imageId);
        }
    }
}

RESOLVED: Issue was due to custom theme not designed/configured properly. Hence I modified the deleteImages function in the theme files to check if image is used more than once (if used once delete image, if more than once then dont delete image):

public function deleteImages(Post $post){
foreach (themeApp('gallery_fields') as $galleryField) {
    /* @var GalleryField $galleryField */
    foreach ($galleryField-getValue($post) as $imageId) {


        $args = array( 'numberposts' = -1, 'fields'='ids');
        $array2 = get_posts( $args );

        foreach($array2 as $item){
            $images = get_post_meta( $item,'customfield_19213');#this is the custom field corresponding to image id

            $imagelist[]=$images;
        }

        foreach ($imagelist as $img){foreach ($img as $im){
            $imageflattened[]=$im;
        }
        }
        $imageflattened=array_count_values($imageflattened);
        $ImageID=strval($imageId);
        $count= $imageflattened[$ImageID];

        if ($count==1){ wp_delete_attachment($imageId);}
    }
}
}

Topic rest-api media posts Wordpress

Category Web

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.