WordPress delete attachment script

I’d like to delete “alternate post” (Apróhirdetések menu) attachment. When I click “Empty trash” I need delete all alternate post and alternate post attachment delete.

I have two half solution.

Read More
  1. I have script. It delete “alternate post” (Apróhirdetések menu) but not delete the attachment. (But I need delete attachment.)

When I click this button, then run script.

Button code:

<button data-toggle="tooltip" data-placement="top" title="<?php _e('Delete','theme-name');?>" onclick="javascript:cs_delete_directory_post('<?php echo esc_js(admin_url('admin-ajax.php'));?>','<?php echo esc_js($post->ID);?>')" type="button" class="tolbtn close close-<?php echo intval($post->ID); ?>" data-dismiss="alert"><em class="icon-trash-o"></em></button>

The script:

function cs_delete_directory_post(admin_url, post_id){
if(confirm('Delete Post')){
        "use strict";
         var dataString = 'post_id=' + post_id+'&action=cs_delete_directory_post';
         jQuery(".close-"+post_id).html('<i style="color:#fe9909;" class="icon-spinner8 icon-spin"></i>');
            jQuery.ajax({
                type:"POST",
                url: admin_url,
                data: dataString,
                success:function(response){
                    jQuery(".attachment-thumbnail").remove();
                    jQuery(".post-"+post_id).remove();
                }
        });
}

return false;
}
  1. I hava verry usefull plugin.
    This plugin delete attachment when I click “Empty Trash”, BUT it only works simple (blog) post. Not work “alternate” post. (picture) But I’ like to work, when I clcik “alternate” post “Empty Trash”.

Plugin:

function wpse_188427_delete_post_media( $post_id ) {
$attachments = get_posts(
    array(
        'post_type'      => 'attachment',
        'posts_per_page' => -1,
        'post_status'    => 'any',
        'post_parent'    => $post_id,
    )
);

foreach ( $attachments as $attachment ) {
    wp_delete_attachment( $attachment->ID );
}
}
add_action( 'delete_post', 'wpse_188427_delete_post_media' );
add_action( 'wp_trash_post', 'wpse_188427_delete_post_media' );

Need any more informations? Big thanks.

Related posts