从POST中删除图像也会从媒体库中删除照片

时间:2017-11-28 作者:Gregory Schultz

有没有一种简单的方法可以从post editor和媒体库中删除图像?

enter image description here

1 个回复
最合适的回答,由SO网友:mysticalghoul 整理而成

不知道是否有一个简单的解决方法,但您可以这样做来实现:

在函数中引入管理js。php如下所示:

//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\' );
} 
js文件将放在您正在使用的主题中,如果js文件不存在,则在js文件中创建另一个名为js的文件夹,代码如下:

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();
                }
            });
        }
      }); 
});
最后,此函数用于执行ajax调用,这也包含在函数中。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\');
如果这对您来说太多,您可以从以下链接下载我为此创建的插件:https://github.com/mysticalghoul/Wordpress-Remove-image-attachment-from-editor

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

让我知道它是否有效!

结束