Remove image from post also removes photo from media library

Is there a simple way that will remove a image from the post editor and the media library?

enter image description here

1 Answer
1

Don’t know if there is an easy way out but you can do this to achieve:

Introduce an admin js in your functions.php like this:

//Admin JS
add_action('admin_init', 'custom_admin_js');
function custom_admin_js() {
    wp_register_script( 'admin-js', get_stylesheet_directory_uri() . '/js/admin.js' );
    wp_enqueue_script( 'admin-js' );
} 

The js file will go in the theme you are using make another folder inside called js if it doesn’t exist and inside the js file this code:

jQuery(document).ready(function($){
    setTimeout(function(){
        var iframeBody = $('body', $('#content_ifr')[0].contentWindow.document);
        $(iframeBody).on('click mousedown', 'img', function(event) {
            var getThisClass = $(this).attr("class").match(/\d+$/)[0];
            var putToThis = $('.mce-toolbar-grp').find($('div:last-child').attr('aria-label', 'Remove').find('button'));
            $(putToThis).attr("att-id", getThisClass);
            $(putToThis).attr("class", "remove-for-good");
        });
     }, 2000);
     $(document).on("click", ".remove-for-good", function(){
        var thisID = $(this).attr("att-id");
        if (confirm('Warning! Remove from Media Also?.')) {
        $.ajax({
                type: 'POST',
                url: ajaxurl,
                data: {
                    action: 'remove_for_good_att',
                    attid: thisID,
                    post_type: 'attachment'
                },
                success: function( html ) {
                    alert( "Sucessfully removed from media also." );
                    $(".media-modal .media-frame-content ul").find($("li.attachment[data-id='" + html + "']")).remove();
                }
            });
        }
      }); 
});

Lastly this function to perform ajax call, this also goes in functions.php

function remove_for_good_att($post){
    global $wpdb;
    $att_id = $_POST['attid'];
    //$ids = $wpdb->get_col("SELECT ID FROM {$wpdb->posts} WHERE post_parent = $att_id AND post_type="attachment"");

    //header( "Content-Type: application/json" );
    if( current_user_can('administrator') ) {
            wp_delete_attachment( $att_id, true );
            print $att_id;
        }
    die();
}
add_action('wp_ajax_remove_for_good_att', 'remove_for_good_att');

If this is too much for you you can download a plugin i created for this purpose from this link: https://github.com/mysticalghoul/Wordpress-Remove-image-attachment-from-editor

Please use latest WordPress version. I tested it on 4.9 and it works

Let me know if it works!

Leave a Comment