private function removeAttachments($post) { $attachments = get_posts(array('post_type' => 'attachment', 'posts_per_page' => -1, 'post_parent' => $post->ID)); foreach ($attachments as $attachment) { wp_delete_attachment($attachment->ID, true); } }
public function deleteImage($image_id, $post_id, $meta_key = false) { wp_delete_attachment($image_id, false); if ($meta_key) { delete_post_meta($post_id, $meta_key, $image_id); } }
/** * Main edit post form * * @global type $wpdb * @global type $userdata */ function prepare_form() { global $wpdb, $userdata; $post_id = isset($_GET['pid']) ? intval($_GET['pid']) : 0; //is editing enabled? if (wpuf_get_option('enable_post_edit', 'yes') != 'yes') { return __('Post Editing is disabled', 'wpuf'); } $curpost = get_post($post_id); if (!$curpost) { return __('Invalid post', 'wpuf'); } //has permission? if (!current_user_can('delete_others_posts') && $userdata->ID != $curpost->post_author) { return __('You are not allowed to edit', 'wpuf'); } //perform delete attachment action if (isset($_REQUEST['action']) && $_REQUEST['action'] == "del") { check_admin_referer('wpuf_attach_del'); $attach_id = intval($_REQUEST['attach_id']); if ($attach_id) { wp_delete_attachment($attach_id); } } //process post if (isset($_POST['wpuf_edit_post_submit']) && wp_verify_nonce($_REQUEST['_wpnonce'], 'wpuf-edit-post')) { $this->submit_post(); } //show post form $this->edit_form($curpost); }
/** * Cron - Thumbnail extraction */ function wp_rp_upload_attachment($url, $post_id) { /* Parts copied from wp-admin/includes/media.php:media_sideload_image */ include_once ABSPATH . 'wp-admin/includes/file.php'; include_once ABSPATH . 'wp-admin/includes/media.php'; include_once ABSPATH . 'wp-admin/includes/image.php'; $tmp = download_url($url); preg_match('/[^\\?]+\\.(jpe?g|jpe|gif|png)\\b/i', $url, $matches); $file_array['name'] = sanitize_file_name(urldecode(basename($matches[0]))); $file_array['tmp_name'] = $tmp; if (is_wp_error($tmp)) { @unlink($file_array['tmp_name']); return false; } $post_data = array('guid' => $url, 'post_title' => 'rp_' . $file_array['name']); $attachment_id = media_handle_sideload($file_array, $post_id, null, $post_data); if (is_wp_error($attachment_id)) { @unlink($file_array['tmp_name']); return false; } $attach_data = wp_get_attachment_metadata($attachment_id); $platform_options = wp_rp_get_platform_options(); $min_width = $platform_options['custom_size_thumbnail_enabled'] ? WP_RP_CUSTOM_THUMBNAILS_WIDTH : WP_RP_THUMBNAILS_WIDTH; $min_height = $platform_options['custom_size_thumbnail_enabled'] ? WP_RP_CUSTOM_THUMBNAILS_HEIGHT : WP_RP_THUMBNAILS_HEIGHT; if (!$attach_data || $attach_data['width'] < $min_width || $attach_data['height'] < $min_height) { wp_delete_attachment($attachment_id); return false; } return $attachment_id; }
function delete_images_permanently($entries) { $meta_key = WPPG_ATTACHMENT_META_TAG; $errors = ''; if (is_array($entries)) { //Remove multiple images from gallery foreach ($entries as $entry) { $result = wp_delete_attachment($entry, true); if ($result == NULL) { $errors .= '<p><strong>' . sprintf(__('The deletion of attachment with image ID %s failed!', 'spgallery'), $entry) . '</strong></p>'; } } } elseif ($entries != NULL) { //Remove a single image from the gallery $result = wp_delete_attachment($entries, true); if ($result == NULL) { $errors .= '<p><strong>' . sprintf(__('The deletion of attachment with image ID %s failed!', 'spgallery'), $entries) . '</strong></p>'; } } if ($errors == '') { $success_msg = '<div id="message" class="updated fade"><p><strong>'; $success_msg .= __('The selected images were successfully deleted from the system permanently!', 'spgallery'); $success_msg .= '</strong></p></div>'; _e($success_msg); } else { $error_msg = '<div id="message" class="error">'; $error_msg .= $errors; $error_msg .= '</div>'; } }
public function delete_attachment() { global $json_api; if (!current_user_can('upload_files') && !current_user_can('delete_posts')) { $json_api->error("You do not have permission to delete files."); } //$json_api->error("Test 1 You do not have permission to delete files."); //return null; $nonce_id = $json_api->get_nonce_id('attachments', 'update_attachment'); if (!wp_verify_nonce($json_api->query->nonce, $nonce_id)) { //$json_api->error("Your 'nonce' value was incorrect. Use the 'get_nonce' API method."); } $id = $json_api->query->id !== null; if ($json_api->query->id !== null) { $id = (int) $json_api->query->id; } else { $json_api->error("Include 'id' or 'slug' var in your request."); } $force_delete = true; if ($json_api->query->force_delete !== null) { $force_delete = (bool) $json_api->query->force_delete; } $result = wp_delete_attachment($id, $force_delete); if ($result) { $successful = true; } else { $successful = false; } $result = array('post' => $result, 'deleted' => (bool) $successful); return $result; }
/** * Delete attachments linked to a specified post * @param int $parent_id Parent id of post to delete attachments for */ function wp_delete_attachments($parent_id, $unlink = true, $type = 'images') { if ($type == 'images' and has_post_thumbnail($parent_id)) { delete_post_thumbnail($parent_id); } $ids = array(); $attachments = get_posts(array('post_parent' => $parent_id, 'post_type' => 'attachment', 'numberposts' => -1, 'post_status' => null)); foreach ($attachments as $attach) { if ($type == 'files' and !wp_attachment_is_image($attach->ID)) { if ($unlink) { wp_delete_attachment($attach->ID, true); } else { $ids[] = $attach->ID; } } elseif ($type == 'images' and wp_attachment_is_image($attach->ID)) { if ($unlink) { wp_delete_attachment($attach->ID, true); } else { $ids[] = $attach->ID; } } } global $wpdb; if (!empty($ids)) { $ids_string = implode(',', $ids); // unattach $result = $wpdb->query("UPDATE {$wpdb->posts} SET post_parent = 0 WHERE post_type = 'attachment' AND ID IN ( {$ids_string} )"); foreach ($ids as $att_id) { clean_attachment_cache($att_id); } } return $ids; }
function expirator_callback() { //get_post_meta( $attachment_id, '_time_to_left', true ); global $post; $args = array('post_type' => 'attachment', 'post_status' => 'inherit', 'posts_per_page' => -1); $loop = new WP_Query($args); $output = ""; while ($loop->have_posts()) { $loop->the_post(); $today = date("Y-m-d"); $today = strtotime($today); $picker = get_post_meta($post->ID, '_time_to_left', true); $picker = strtotime($picker); if ($picker != '') { $output .= 'process ' . $post->ID . ' >> ' . $today . ':' . $picker . '</br>'; if ($today >= $picker) { $output .= 'this true - remove it</br>'; wp_delete_attachment($post->ID, true); } $output .= '</br></br>'; } } //send mail about expiration status //wp_mail( '*****@*****.**', 'expirator', $output ); }
/** * Delete all wordpress attachments * for a particular post. * * @param null $postId * * @return array */ public function deleteAttachments($postId = NULL) { // Data must be sent if (is_null($postId)) { return 'Must provide post ID to delete attachments.'; } // Init a results array $results = array(); // Get attachments $attachments = get_posts(array('post_type' => 'attachment', 'posts_per_page' => -1, 'post_status' => 'any', 'post_parent' => $postId)); // Loop through attachments foreach ($attachments as $attachment) { // Delete this attachment. $result = wp_delete_attachment($attachment->ID, true); // If deletion was successful... if ($result) { // Add id to success array. $results[] = $attachment->ID; } else { // Warn the user... echo "Warning! : Attachment could not be deleted: " . $attachment->ID; } } // Return results. return $results; }
/** @brief threewp_broadcast_apply_existing_attachment_action @since 2015-11-16 14:10:32 **/ public function threewp_broadcast_apply_existing_attachment_action($action) { if ($action->is_finished()) { return; } $bcd = $action->broadcasting_data; switch ($action->action) { case 'overwrite': // Delete the existing attachment $this->debug('Maybe copy attachment: Deleting current attachment %s', $action->target_attachment->ID); wp_delete_attachment($action->target_attachment->ID, true); // true = Don't go to trash // Tell BC to copy the attachment. $action->use = false; break; case 'randomize': $filename = $bcd->attachment_data->filename_base; $filename = preg_replace('/(.*)\\./', '\\1_' . rand(1000000, 9999999) . '.', $filename); $bcd->attachment_data->filename_base = $filename; $this->debug('Maybe copy attachment: Randomizing new attachment filename to %s.', $bcd->attachment_data->filename_base); // Tell BC to copy the attachment. $action->use = false; break; } }
/** * Tear down the test fixture. */ public function tearDown() { // Cleanup foreach ($this->_ids as $id) { wp_delete_attachment($id, true); } parent::tearDown(); }
/** * [delet_attachment write data from wordpress to CSV] * @param [type] $post_id [description] * @return [type] [description] */ public function delete_attachment( $post ) { global $wpdb; //$ids = $wpdb->get_col("SELECT ID FROM {$wpdb->posts} WHERE post_parent = $post_id AND post_type = 'attachment'"); $ids = $wpdb->get_col("SELECT ID FROM {$wpdb->posts} WHERE post_type = 'attachment'"); foreach ( $ids as $id ) wp_delete_attachment($id); }
public function import_roles() { if (!$this->can_import()) { $this->main->permission_denied(); return; } if (!extension_loaded('simplexml')) { echo '<div class="error"><p>' . $this->__('This functionality requires SimpleXML extension, which is not loaded.') . '</p></div>'; return; } if (!empty($_POST['submit'])) { check_admin_referer('import-upload'); set_time_limit(0); if ($this->handle_upload()) { $this->roles_data = array(); global $wp_roles; foreach ($this->import_data->roles as $role) { $this->roles_data[$role->name] = (object) array('display_name' => $role->display_name, 'override' => FALSE); if (get_role($role->name) !== NULL) { $this->roles_data[$role->name]->override = TRUE; } } } } if (!empty($_POST['importroles'])) { $this->main->verify_nonce(); set_time_limit(0); if (!empty($_POST['file-id'])) { $this->file_id = $_POST['file-id']; $this->parse_contents(get_attached_file($this->file_id)); if (is_wp_error($this->import_data)) { $this->result = (object) array('success' => FALSE, 'message' => $this->import_data->get_error_message()); $this->import_data = NULL; } else { $this->roles_data = array(); if (!empty($_POST['import-roles'])) { $this->roles_data = $_POST['import-roles']; if (!is_array($this->roles_data)) { $this->roles_data = array(); } } foreach ($this->import_data->roles as $role) { if (array_key_exists($role->name, $this->roles_data)) { if (get_role($role->name) === NULL) { add_role($role->name, $role->display_name, $role->capabilities); } else { WPFront_User_Role_Editor_Add_Edit::update_role($role->name, $role->display_name, $role->capabilities); } } } $this->result = (object) array('success' => TRUE, 'message' => sprintf($this->__('%d role(s) imported.'), count($this->roles_data))); $this->import_data = NULL; } wp_delete_attachment($this->file_id); } } include $this->main->pluginDIR() . 'templates/personal-pro/import-roles.php'; }
function tzs_delete_auction_callback() { $id = isset($_POST['id']) && is_numeric($_POST['id']) ? intval($_POST['id']) : 0; $is_delete = isset($_POST['is_delete']) && is_numeric($_POST['is_delete']) ? intval($_POST['is_delete']) : 0; $user_id = get_current_user_id(); $errors = array(); if ($id <= 0) { echo "Номер не найден"; } else { if ($user_id == 0) { echo "Вход в систему обязателен"; } else { global $wpdb; // Добавить проверку наличия ставок - если есть ставки, то удаление невозможно $sql = "SELECT COUNT(*) as cnt FROM " . TZS_AUCTION_RATES_TABLE . " WHERE auction_id = {$id}"; $row = $wpdb->get_row($sql); if (count($row) === 0 && $wpdb->last_error != null) { echo 'Не удалось отобразить информацию о ставках по тендеру. Свяжитесь, пожалуйста, с администрацией сайта.'; echo $wpdb->last_error; } else { if ($row === null) { echo 'Ставки по тендеру не найдены.'; } else { if ($row->cnt > 0) { echo 'Обнаружены ставки по тендеру, удаление записи невозможно.'; } else { if (strlen($row->image_id_lists) > 0 && $is_delete === 1) { $img_names = explode(';', $row->image_id_lists); for ($i = 0; $i < count($img_names); $i++) { if (false === wp_delete_attachment($img_names[$i], true)) { echo "Не удалось удалить файл с изображением: " . $img_names[$i]->get_error_message(); array_push($errors, "Не удалось удалить файл с изображением: " . $img_names[$i]->get_error_message()); } } } if (count($errors) === 0) { if ($is_delete === 1) { $sql = "DELETE FROM " . TZS_AUCTIONS_TABLE . " WHERE id={$id} AND user_id={$user_id};"; } else { $sql = "UPDATE " . TZS_AUCTIONS_TABLE . " SET active=0 WHERE id={$id} AND user_id={$user_id};"; } if (false === $wpdb->query($sql)) { if ($is_delete === 1) { echo "Не удалось удалить Ваш тендер. Свяжитесь, пожалуйста, с администрацией сайта "; } else { echo "Не удалось перенести в архив Ваш тендер. Свяжитесь, пожалуйста, с администрацией сайта "; } } else { echo "1"; } } } } } } } die; }
function delete_attachment($post) { //echo $_POST['att_ID']; $msg = 'Attachment ID [' . $_POST['att_ID'] . '] has been deleted!'; if (wp_delete_attachment($_POST['att_ID'], true)) { echo $msg; } die; }
function delete_file($attach_id) { $attachment = get_post($attach_id); //post author or editor role if (get_current_user_id() == $attachment->post_author || current_user_can('delete_private_pages')) { wp_delete_attachment($attach_id, true); return true; } exit; }
function rssmi_delete_attachment($id_ID) { $args = array('post_type' => 'attachment', 'numberposts' => -1, 'post_status' => 'any', 'post_parent' => $id_ID); $attachments = get_posts($args); if ($attachments) { foreach ($attachments as $attachment) { wp_delete_attachment($attachment->ID, true); } } }
/** * Delete the attachments of a parent post * * @param $pid */ function rssmi_delete_attachment($pid) { $attachments = get_children(array('post_type' => 'attachment', 'posts_per_page' => -1, 'post_status' => 'any', 'post_parent' => $pid)); if (empty($attachments)) { return; } foreach ($attachments as $attachment) { wp_delete_attachment($attachment->ID, TRUE); } }
function rssmi_uninstall_delete_attachment($id_ID) { // DELETE ATTACHMENTS CREATED BY THIS PLUGIN $args = array('post_type' => 'attachment', 'numberposts' => -1, 'post_status' => 'any', 'post_parent' => $id_ID); $attachments = get_posts($args); if ($attachments) { foreach ($attachments as $attachment) { wp_delete_attachment($attachment->ID, true); } } }
/** * Delete the attachments related to the specified post. * * @param $post_id */ function wl_delete_post_attachments($post_id) { // Get all the attachments related to the post. $attachments = wl_get_attachments($post_id); // Delete each attachment. foreach ($attachments as $attachment) { if (false === wp_delete_attachment($attachment->ID)) { wl_write_log("wl_delete_post_attachments : error [ post id :: {$post_id} ]"); } } }
/** * Clean up attachments when we delete a submission * * @param int $post_id * @since 6.4 */ public function action_before_delete_post($post_id) { if ('ccf_submission' === get_post_type($post_id)) { $attachments = get_children(array('post_parent' => $post_id, 'numberposts' => apply_filters('ccf_max_submission_attachments', 5000, get_post($post_id)))); if (!empty($attachments)) { foreach ($attachments as $attachment) { wp_delete_attachment($attachment->ID, true); } } } }
function siw_delete_attachment_after_mail($entry_id, $form_id) { global $wpdb; $attachments_args = array('post_type' => 'attachment', 'post_parent' => $entry_id, 'fields' => 'ids'); $attachments = get_posts($attachments_args); foreach ($attachments as $attachment) { $attachment_url = wp_get_attachment_url($attachment); wp_delete_attachment($attachment); $wpdb->query($wpdb->prepare("UPDATE {$wpdb->postmeta}\n\t\t\t\tSET meta_value = 'gemaild'\n\t\t\t\t\tWHERE post_id = %d\n\t\t\t\t\tAND meta_value = %s;", $entry_id, $attachment_url)); } }
/** * Delete attachment (and associated files) * * @return boolean success */ protected function delete_post() { if ($this->post->post_type == 'attachment') { $this->pmp_debug("** deleting stale attachment"); wp_delete_attachment($this->post->ID, true); } else { $this->pmp_debug("** deleting stale {$this->post->post_type}"); wp_delete_post($this->post->ID, true); } return true; }
/** * Tear down the test fixture. */ public function tearDown() { foreach ($this->ids as $id) { wp_delete_attachment($id, true); } $uploads = wp_upload_dir(); foreach (scandir($uploads['basedir']) as $file) { $this->rmdir($uploads['basedir'] . '/' . $file); } parent::tearDown(); }
function tzs_delete_product_callback() { $id = isset($_POST['id']) && is_numeric($_POST['id']) ? intval($_POST['id']) : 0; $is_delete = isset($_POST['is_delete']) && is_numeric($_POST['is_delete']) ? intval($_POST['is_delete']) : 0; $user_id = get_current_user_id(); $errors = array(); if ($id <= 0) { echo "Товар/услуга не найден"; } else { if ($user_id == 0) { echo "Вход в систему обязателен"; } else { global $wpdb; // Вначале попытаемся удалить изображения $sql = "SELECT * FROM " . TZS_PRODUCTS_TABLE . " WHERE id={$id} AND user_id={$user_id};"; $row = $wpdb->get_row($sql); if (count($row) === 0 && $wpdb->last_error != null) { echo 'Не удалось получить список товаров. Свяжитесь, пожалуйста, с администрацией сайта'; echo $wpdb->last_error; } else { if ($row === null) { echo "Товар/услуга не найден (id={$id} AND user_id={$user_id})"; } else { if (strlen($row->image_id_lists) > 0 && $is_delete === 1) { $img_names = explode(';', $row->image_id_lists); for ($i = 0; $i < count($img_names); $i++) { if (false === wp_delete_attachment($img_names[$i], true)) { echo "Не удалось удалить файл с изображением: " . $img_names[$i]->get_error_message(); array_push($errors, "Не удалось удалить файл с изображением: " . $img_names[$i]->get_error_message()); } } } if (count($errors) === 0) { if ($is_delete === 1) { $sql = "DELETE FROM " . TZS_PRODUCTS_TABLE . " WHERE id={$id} AND user_id={$user_id};"; } else { $sql = "UPDATE " . TZS_PRODUCTS_TABLE . " SET active=0 WHERE id={$id} AND user_id={$user_id};"; } if (false === $wpdb->query($sql)) { if ($is_delete === 1) { echo "Не удалось удалить Ваш товар/услугу. Свяжитесь, пожалуйста, с администрацией сайта "; } else { echo "Не удалось перенести в архив Ваш товар/услугу. Свяжитесь, пожалуйста, с администрацией сайта "; } } else { echo "1"; } } } } } } die; }
/** * Delete a featured image via ajax * * @since 0.8 */ function featured_img_delete() { check_ajax_referer('wpuf_nonce', 'nonce'); $attach_id = isset($_POST['attach_id']) ? intval($_POST['attach_id']) : 0; $attachment = get_post($attach_id); //post author or editor role if (get_current_user_id() == $attachment->post_author || current_user_can('delete_private_pages')) { wp_delete_attachment($attach_id, true); echo 'success'; } exit; }
/** * Delete an attachmant from a product */ function ajax_delete_product_thumbnail() { check_ajax_referer('wpshop_delete_product_thumbnail', 'wpshop_ajax_nonce'); $bool = false; $attachement_id = isset($_POST['attachement_id']) ? intval(wpshop_tools::varSanitizer($_POST['attachement_id'])) : null; if (!empty($attachement_id)) { $deletion_result = wp_delete_attachment($attachement_id, false); $bool = !empty($deletion_result); } echo json_encode(array($bool, $attachement_id)); die; }
function delete_pic_cover_group($activity_id) { global $bp; $group_id = $bp->groups->current_group->id; $activity_id = $_POST['activity_id']; $attachment_id = bp_activity_get_meta($activity_id, 'all_bp_cover_group', true); wp_delete_attachment($attachment_id, true); groups_delete_groupmeta($group_id, 'bp_cover_group'); groups_delete_groupmeta($group_id, 'bp_cover_group_position'); bp_activity_delete(array('id' => $activity_id, 'item_id' => $group_id)); BP_Activity_Activity::delete_activity_meta_entries($activity_id); }
/** * Sets listing images. * @param array $images array of image IDs. * @param boolean $append if TRUE images will be appended without clearing previous ones. */ public function set_images($images = array(), $append = false) { if (!$append) { $current = $this->get_images('ids'); foreach ($current as $img_id) { if (!in_array($img_id, $images, true) && wp_attachment_is_image($img_id)) { wp_delete_attachment($img_id, true); } } } foreach ($images as $image_id) { wp_update_post(array('ID' => $image_id, 'post_parent' => $this->id)); } }
/** * Ajax callback for deleting files. * Modified from a function used by "Verve Meta Boxes" plugin * * @link http://goo.gl/LzYSq * @return void */ static function wp_ajax_delete_file() { $post_id = isset($_POST['post_id']) ? intval($_POST['post_id']) : 0; $field_id = isset($_POST['field_id']) ? $_POST['field_id'] : 0; $attachment_id = isset($_POST['attachment_id']) ? intval($_POST['attachment_id']) : 0; check_admin_referer("rwmb-delete-file_{$field_id}"); $ok = delete_post_meta($post_id, $field_id, $attachment_id); $ok = $ok && wp_delete_attachment($attachment_id); if ($ok) { RW_Meta_Box::ajax_response('', 'success'); } else { RW_Meta_Box::ajax_response(__('Error: Cannot delete file', 'bootstrap'), 'error'); } }