如何干净利落地删除附件而保留原始文件?

时间:2011-02-17 作者:Rarst

wp_delete_attachment() 非常全面,可以清除数据库和磁盘中的所有附件痕迹。

有没有保存原始文件的简单方法?不能使用其他名称进行分叉,因为其他函数wp_delete_post() 仍将调用原始版本。

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

一年后,一些人的技能有了很大的提高,你看:

Keep_Deleted_Attachment_File::on_load();

/**
 * Keep original file when deleting attachments.
 */
class Keep_Deleted_Attachment_File {

    static private $file;

    static function on_load() {

        add_action( \'init\', array( __CLASS__, \'init\' ) );
    }

    static function init() {

        add_action( \'delete_attachment\', array( __CLASS__, \'delete_attachment\' ) );
    }

    /**
     * @param int $post_id attachment being deleted
     */
    static function delete_attachment( $post_id ) {

        self::$file = get_attached_file( $post_id );
        add_filter( \'wp_delete_file\', array( __CLASS__, \'wp_delete_file\' ) );
    }

    /**
     * @param string $file path to file being deleted
     *
     * @return string|bool no change or boolean false to prevent file deletion
     */
    static function wp_delete_file( $file ) {

        if ( ! empty( self::$file ) && self::$file == $file ) {

            remove_filter( current_filter(), array( __CLASS__, __FUNCTION__ ) );
            return false;
        }

        return $file;
    }
}

SO网友:John P Bloch

假设$attachment_id 是要在不删除文件的情况下删除的附件的ID,应执行以下操作:

$wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->posts, $wpdb->postmeta WHERE $wpdb->posts.ID = %d OR $wpdb->postmeta.post_id = %d", $attachment_id, $attachment_id ) );

结束

相关推荐