Skip to content

Instantly share code, notes, and snippets.

@BruceMcKinnon
Created July 30, 2020 03:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save BruceMcKinnon/16e78a71c9d171e8fd106227334e94a6 to your computer and use it in GitHub Desktop.
Save BruceMcKinnon/16e78a71c9d171e8fd106227334e94a6 to your computer and use it in GitHub Desktop.
Gravity Forms - Button to delete file uploads for an entry
add_filter( 'gform_entry_detail_meta_boxes', 'add_delete_attachment_meta_box', 10, 3 );
function add_delete_attachment_meta_box( $meta_boxes, $entry, $form ) {
$my_form_id = 3;
if ( $form['id'] == $my_form_id ) {
if ( ! isset( $meta_boxes['payment'] ) ) {
$meta_boxes['payment'] = array(
'title' => esc_html__( 'Delete Attachments', 'gravityforms' ),
'callback' => 'meta_box_delete_attachments',
'context' => 'side',
'callback_args' => array( $entry, $form ),
);
}
}
return $meta_boxes;
}
function meta_box_delete_attachments( $args ) {
$html = '<div class="wrap">';
// Check whether the button has been pressed AND also check the nonce
if (isset($_POST['delete_attachment_button']) && check_admin_referer('delete_attachment_button_clicked')) {
// the button has been pressed AND we've passed the security check
delete_these_attachments( $args );
}
$html .= '<form action="options-general.php?page=delete-attachment-button-slug" method="post">';
// this is a WordPress security feature - see: https://codex.wordpress.org/WordPress_Nonces
wp_nonce_field('delete_attachment_button_clicked');
$html .= '<input type="hidden" value="true" name="delete_attachment_button" />';
submit_button('Delete Attachments');
$html .= '</form>';
$html .= '<p style="color:red;"><strong>WARNING - Make sure you download the attachments before deleting. They will be deleted as soon as you click the button.</strong></p>';
$html .= '</div>';
echo $html;
}
function delete_these_attachments( $args ) {
$form = $args['form'];
$entry = $args['entry'];
$fileupload_fields = array();
// Find all of the FileUpload fields
foreach( $form['fields'] as $field ) {
if ($field['type'] == 'fileupload') {
array_push($fileupload_fields,$field['id']);
}
}
$wp_dirs = wp_upload_dir();
$delete_count = 0;
if ( count($fileupload_fields) > 0 ) {
foreach( $fileupload_fields as $field_id ) {
$attachment_url = $entry[$field_id];
$attachment_abs = str_ireplace( $wp_dirs['baseurl'], $wp_dirs['basedir'], $attachment_url );
if ( file_exists( $attachment_abs ) ) {
if ( unlink($attachment_abs) ) {
$delete_count += 1;
}
}
}
}
echo '<div id="message" class="updated fade"><p>'.$delete_count.' attachments(s) deleted.' . '</p></div>';
?>
<?php
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment