delete image with id from DB wordpress

I want to delete image with it's ID from PHPMyAdmin DB. Table with images is wp_posts and ID is called post_parent. Action that connects to ajax and should delete image:

add_action( 'wp_ajax_delete_image_admin', 'delete_image_admin' );
function delete_image_admin(){

    $deleteId = $_POST['deletedId'];

    
    
    $return = array(
    'message'   => 'Сохранено',
    'ID'        => $_POST['deletedId'],
);
wp_send_json( $return );
};

Ajax (it's working correctly):

<script>
jQuery(document).ready(function($) {
  $(document).on('click', '.image-remove-btn', function (e){
    e.preventDefault();
    var img = $(this).closest('.thumbs');
    var id = img.find("img").data('id');
    $.ajax({
        url: "/wp-admin/admin-ajax.php",
        type: 'POST',
        data: {deletedId : id,
        action: "delete_image_admin"},
        success: function( data ) {
            img.remove();
        }    
    });
  });
});
</script>

1 answer

  • answered 2021-05-14 16:08 Csikós Zoltán

    The following code should delete the image from wp_posts table:

    add_action('wp_ajax_delete_image_admin', 'delete_image_admin');
    add_action('wp_ajax_nopriv_delete_image_admin', 'delete_image_admin');
    function delete_image_admin(){
        if (!empty($_POST['deletedId'])) {
            global $wpdb;
    
            $deleteId = $_POST['deletedId'];
    
            $table = $wpdb->base_prefix . "posts";
            $wpdb->delete($table, [
                'ID' => $deleteId,
            ]);
    
            echo 'Image deleted';
    
            wp_die();
        }
    };