Skip to content

Instantly share code, notes, and snippets.

@sungraiz
Created December 24, 2019 16:54
Show Gist options
  • Save sungraiz/db3b5318409561a29a1061a4d18b90bd to your computer and use it in GitHub Desktop.
Save sungraiz/db3b5318409561a29a1061a4d18b90bd to your computer and use it in GitHub Desktop.
<style>
.rh_form__item #attachment-thumbs-container {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-flex-wrap: wrap;
-ms-flex-wrap: wrap;
flex-wrap: wrap;
}
.rh_form__item #attachment-thumbs-container .attachment-thumb {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-box-align: center;
-webkit-align-items: center;
-ms-flex-align: center;
align-items: center;
-webkit-box-pack: center;
-webkit-justify-content: center;
-ms-flex-pack: center;
justify-content: center;
background: #F7F7F7;
position: relative;
margin: 0 1.5rem 1.5rem 0;
padding: 1rem;
font-size: 1.4rem;
color: #808080;
}
.rh_form__item #attachment-thumbs-container .attachment-thumb span:first-child i.fa{
display: inline-block;
font-size: 7rem;
margin-right: 1.5rem;
color: #676666;
}
.rh_form__item #attachment-thumbs-container .attachment-thumb span:first-child{
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-box-align: center;
-webkit-align-items: center;
-ms-flex-align: center;
align-items: center;
color: #676666;
}
.rh_form__item #attachment-thumbs-container .attachment-thumb .remove-attachment {
position: absolute;
right: 0;
bottom: 0;
background: rgba(0, 0, 0, 0.5);
color: #fff;
padding: 0.5rem 0.8rem;
}
.rh_form__item #attachment-thumbs-container .attachment-thumb .loader {
display: none;
position: absolute;
top: 0;
right: 0;
background: rgba(0, 0, 0, 0.5);
color: #fff;
padding: 0.5rem 0.8rem;
}
.rh_form__item #attachment-drag-and-drop {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-box-pack: center;
-webkit-justify-content: center;
-ms-flex-pack: center;
justify-content: center;
-webkit-box-align: center;
-webkit-align-items: center;
-ms-flex-align: center;
align-items: center;
-webkit-box-orient: vertical;
-webkit-box-direction: normal;
-webkit-flex-direction: column;
-ms-flex-direction: column;
flex-direction: column;
height: 30rem;
background: #F7F7F7;
border: 1px dashed rgba(128, 128, 128, 0.2);
font: 500 1.5rem/1.5 "Rubik", sans-serif;
}
@media only screen and (min-width: 1140px){
.rh_form__item #attachment-drag-and-drop {
-webkit-box-orient: horizontal;
-webkit-box-direction: normal;
-webkit-flex-direction: row;
-ms-flex-direction: row;
flex-direction: row;
}
}
.rh_form__item #attachment-drag-and-drop div {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
margin: 1rem 0;
}
.rh_form__item #attachment-drag-and-drop .attachment_limit_left {
position: absolute;
left: 0;
bottom: 0;
}
.rh_form__item .rh_attachment_max_file_limit_message {
position: relative;
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-box-pack: center;
-webkit-justify-content: center;
-ms-flex-pack: center;
justify-content: center;
-webkit-box-align: center;
-webkit-align-items: center;
-ms-flex-align: center;
align-items: center;
-webkit-box-orient: vertical;
-webkit-box-direction: normal;
-webkit-flex-direction: column;
-ms-flex-direction: column;
flex-direction: column;
height: 30rem;
background: #F7F7F7;
border: 1px dashed rgba(128, 128, 128, 0.2);
font: 500 1.5rem/1.5 "Rubik", sans-serif;
color: red;
}
.rh_form__item .rh_attachment_max_file_limit_message.hide {
display: none;
}
.rh_form__item #attachment-errors-log {
color: #808080;
font: 400 1.4rem/1.5 "Rubik", sans-serif;
}
.rh_form__item #attachment-drag-and-drop .attachment_limit_left {
position: absolute;
left: 0;
bottom: 0;
}
.rh_form__item #attachment-drag-and-drop div {
margin: 0 1rem;
}
</style>
<?php
add_action( 'inspiry_additional_edit_property_fields', 'add_property_attachment_frontend' );
add_action( 'inspiry_additional_submit_property_fields', 'add_property_attachment_frontend' );
function add_property_attachment_frontend(){
global $column_class;
global $target_property;
?>
<div class="rh_form__item <?php echo esc_attr( $column_class ); ?> rh_form--columnAlign attachment-field-wrapper">
<?php
if ( inspiry_is_edit_property() ) {
?>
<div id="attachment-thumbs-container" class="clearfix">
<?php
$attachments = get_post_meta( $target_property->ID , 'REAL_HOMES_attachments' );
if ( is_array( $attachments ) ) {
$attachments = array_filter( $attachments );
$attachments = array_unique( $attachments );
}
if ( ! empty( $attachments ) ) {
foreach ( $attachments as $attachment_id ) {
$file_path = wp_get_attachment_url( $attachment_id );
if ( $file_path ) {
$file_type = wp_check_filetype( $file_path );
echo '<div class="attachment-thumb">';
echo '<span class="' . esc_attr( $file_type['ext'] ) . '">' . get_icon_for_extension( $file_type['ext'] ) . get_the_title( $attachment_id ) . '</span>';
echo '<a class="remove-attachment" data-property-id="' . esc_attr( $target_property->ID ) . '" data-attachment-id="' . esc_attr( $attachment_id ) . '" href="#remove-attachment" ><i class="fa fa-trash-o"></i></a>';
echo '<span class="loader"><i class="fa fa-spinner fa-spin"></i></span>';
echo '<input type="hidden" class="attachment-id" name="property_attachment_ids[]" value="' . esc_attr( $attachment_id ) . '"/>';
echo '</div>';
}
}
} ?>
</div>
<?php
} else {
?>
<div id="attachment-thumbs-container" class="clearfix"></div>
<?php
}
if ( isset( $target_property ) &&
get_post_meta( $target_property->ID, 'REAL_HOMES_attachments', false ) &&
! empty( get_post_meta( $target_property->ID, 'REAL_HOMES_attachments', false ) ) ) {
$get_attachments_count = count( array_filter( get_post_meta( $target_property->ID, 'REAL_HOMES_attachments', false ) ) );
} else {
$get_attachments_count = 0;
}
$inspiry_submit_max_number_attachments = get_option( 'inspiry_submit_max_number_images', 48 );
?>
<div id="attachment-drag-and-drop" class="rh_attachment_drag_and_drop_wrapper <?php if ( $get_attachments_count == $inspiry_submit_max_number_attachments ) {
echo esc_attr( 'hide' );
}; ?>" data-max-attachments="<?php echo esc_attr( $inspiry_submit_max_number_attachments ) ?>">
<div class="attachment-drag-drop-msg">
<i class="fa fa-cloud-upload"></i>&nbsp;
&nbsp;<?php esc_html_e( 'Drag and drop attachments here', 'framework' ); ?>
</div>
<div class="attachment-drag-or"><?php esc_html_e( 'or', 'framework' ); ?></div>
<div class="attachment-drag-btn">
<button id="select-attachments" class="rh_btn rh_btn--secondary">
<?php esc_html_e( 'Browse attachments', 'framework' ); ?>
</button>
</div>
<!-- </div>-->
<div class="attachment_limit_left">
<span class="attachment-uploaded"><?php echo esc_html( $get_attachments_count ); ?></span>
<?php echo '/' ?>
<?php echo esc_html( $inspiry_submit_max_number_attachments ); ?>
</div>
</div>
<div class="rh_max_attachment_limit_message <?php if ( $get_attachments_count < $inspiry_submit_max_number_attachments ) {
echo esc_attr( 'hide' );
}; ?>">
<p><?php esc_html_e( 'You have reached maximum files upload limit', 'framework' ); ?></p>
<div class="attachment_limit_left">
<span class="attachment-uploaded"><?php echo esc_html( $get_attachments_count ); ?></span>
<?php echo '/' ?>
<?php echo esc_html( $inspiry_submit_max_number_attachments ); ?>
</div>
</div>
<div class="field-description">
<span class="rh_attachment_max_files_limit_message hide"><?php printf( esc_html__( 'Your selected files are exceeding from limit of %s ', 'framework' ), $inspiry_submit_max_number_attachments ); ?></span>
</div>
<div id="attachment-errors-log"></div>
</div>
<!-- /.rh_form__item -->
<?php
}
/**
* Ajax image upload for property submit and update
*/
function inspiry_attachment_upload() {
global $target_property;
// Verify Nonce
$nonce = $_REQUEST[ 'nonce' ];
if ( ! wp_verify_nonce( $nonce, 'inspiry_allow_upload' ) ) {
$ajax_response = array(
'success' => false,
'reason' => esc_html__( 'Security check failed!', 'framework' ),
);
echo wp_json_encode( $ajax_response );
die;
}
$submitted_file = $_FILES[ 'inspiry_upload_file' ];
$uploaded_attachment = wp_handle_upload( $submitted_file, array( 'test_form' => false ) ); //Handle PHP uploads in WordPress, sanitizing file names, checking extensions for mime type, and moving the file to the appropriate directory within the uploads directory.
if ( isset( $uploaded_attachment[ 'file' ] ) ) {
$file_name = basename( $submitted_file[ 'name' ] );
$file_type = wp_check_filetype( $uploaded_attachment[ 'file' ] ); // Retrieve the file type from the file name.
if ( preg_match( '/(image|plain|text|pdf|zip)$/', $file_type[ 'type' ] ) ){
// Prepare an array of post data for the attachment.
$attachment_details = array(
'guid' => $uploaded_attachment[ 'url' ],
'post_mime_type' => $file_type[ 'type' ],
'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $file_name ) ),
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment_details, $uploaded_attachment[ 'file' ] ); // This function inserts an attachment into the media library
$attach_data = wp_generate_attachment_metadata( $attach_id, $uploaded_attachment[ 'file' ] ); // This function generates metadata for an image attachment. It also creates a thumbnail and other intermediate sizes of the image attachment based on the sizes defined
if ( !empty( $attach_data ) ) {
wp_update_attachment_metadata( $attach_id, $attach_data ); // Update metadata for an attachment.
$ajax_response = array( 'success' => true, 'attachment_id' => $attach_id, 'type' => $file_type[ 'type' ] );
echo wp_json_encode( $ajax_response );
die;
}else{
$ajax_response = array( 'success' => true, 'attachment_id' => $attach_id, 'type' => $file_type[ 'type' ], 'post_title' => get_the_title($attach_id), );
echo wp_json_encode( $ajax_response );
die;
}
}else{
$ajax_response = array( 'success' => false, 'reason' => esc_html__( 'Invalid Attachment format!' . wp_json_encode($file_type),'framework' ) );
echo wp_json_encode( $ajax_response );
die;
}
} else {
$ajax_response = array( 'success' => false, 'reason' => esc_html__( 'Attachment upload failed!', 'framework' ) );
echo wp_json_encode( $ajax_response );
die;
}
}
add_action( 'wp_ajax_ajax_attachment_upload', 'inspiry_attachment_upload' ); // only for logged in user
function inspiry_remove_property_attachment() {
// Verify Nonce
$nonce = $_POST[ 'nonce' ];
if ( ! wp_verify_nonce( $nonce, 'inspiry_allow_upload' ) ) {
$ajax_response = array(
'post_meta_removed' => false,
'attachment_removed' => false,
'reason' => esc_html__('Security check failed!', 'framework')
);
echo json_encode( $ajax_response );
die;
}
$post_meta_removed = false;
$attachment_removed = false;
if ( isset( $_POST[ 'property_id' ] ) && isset( $_POST[ 'attachment_id' ] ) ) {
$property_id = intval( $_POST[ 'property_id' ] );
$attachment_id = intval( $_POST[ 'attachment_id' ] );
if ( $property_id > 0 && $attachment_id > 0 ) {
$post_meta_removed = delete_post_meta( $property_id, 'REAL_HOMES_attachments', $attachment_id );
$attachment_removed = wp_delete_attachment( $attachment_id );
} else if ( $attachment_id > 0 ) {
if ( false === wp_delete_attachment( $attachment_id ) ) {
$attachment_removed = false;
} else {
$attachment_removed = true;
}
}
}
$ajax_response = array(
'post_meta_removed' => $post_meta_removed,
'attachment_removed' => $attachment_removed,
);
echo json_encode( $ajax_response );
die;
}
add_action( 'wp_ajax_remove_property_attachment', 'inspiry_remove_property_attachment' );
add_action('inspiry_after_property_submit', 'inspiry_submit_fields_database');
add_action('inspiry_after_property_update', 'inspiry_submit_fields_database');
function inspiry_submit_fields_database($id){
if ( isset( $_POST['property_attachment_ids'] ) ) {
if ( ! empty( $_POST['property_attachment_ids'] ) && is_array( $_POST['property_attachment_ids'] ) ) {
foreach ( $_POST['property_attachment_ids'] as $attachment_image_id ) {
add_post_meta( $id, 'REAL_HOMES_attachments', $attachment_image_id );
}
}
}
}
?>
<script>
/* Child Theme - Custom JS File for Users to add their own JS code */
(function ($) {
"use strict";
function get_icon_for_extension( $ext ) {
switch ( $ext ) {
/* PDF */
case 'pdf':
return '<i class="fa fa-file-pdf-o"></i>';
/* Images */
case 'image':
return '<i class="fa fa-file-image-o"></i>';
/* Text */
case 'plain':
case 'txt':
case 'log':
case 'tex':
return '<i class="fa fa-file-text-o"></i>';
/* Documents */
case 'doc':
case 'odt':
case 'msg':
case 'docx':
case 'rtf':
case 'wps':
case 'wpd':
case 'pages':
return '<i class="fa fa-file-word-o"></i>';
/* Spread Sheets */
case 'csv':
case 'xlsx':
case 'xls':
case 'xml':
case 'xlr':
return '<i class="fa fa-file-excel-o"></i>';
/* Zip */
case 'zip':
case 'rar':
case '7z':
case 'zipx':
case 'tar.gz':
case 'gz':
case 'pkg':
return '<i class="fa fa-file-zip-o"></i>';
/* Others */
default:
return '<i class="fa fa-file-o"></i>';
}
}
if ( typeof propertySubmit !== "undefined" ) {
var removeQueryStringParameters = function (url) {
if (url.indexOf('?') >= 0) {
var urlParts = url.split('?');
return urlParts[0];
}
return url;
};
var ajaxURL = removeQueryStringParameters(propertySubmit.ajaxURL);
var uploadNonce = propertySubmit.uploadNonce;
var fileTypeTitle = propertySubmit.fileTypeTitle;
/* Apply jquery ui sortable on attachment items */
$("#attachment-thumbs-container").sortable({
revert: 100,
connectWith: "#attachment-thumbs-container",
placeholder: "ui-state-highlight",
cursor: "move"
}).disableSelection();
/* initialize uploader */
var uploaderArguments = {
browse_button: 'select-attachments', // this can be an id of a DOM element or the DOM element itself
file_data_name: 'inspiry_upload_file',
drop_element: 'attachment-drag-and-drop',
url: ajaxURL + "?action=ajax_attachment_upload&nonce=" + uploadNonce,
filters: {
mime_types: [
{title: fileTypeTitle, extensions: "jpg,jpeg,png,txt,pdf,zip"}
],
max_file_size: '10000kb',
// prevent_duplicates: true
},
};
var uploader = new plupload.Uploader(uploaderArguments);
uploader.init();
uploader.bind('FilesAdded', function (up, files) {
var currentImages = $('.attachment-thumb').length;
var getMaxfiles = $('.rh_attachment_drag_and_drop_wrapper').data('max-attachments');
var totalFiles = currentImages + up.files.length;
if (totalFiles > getMaxfiles) {
up.splice(up.settings.totalFiles);
$('.rh_attachment_max_files_limit_message').addClass('show');
return false;
} else {
$('.rh_attachment_max_files_limit_message').removeClass('show');
}
});
$('#select-attachments').click(function (event) {
event.preventDefault();
event.stopPropagation();
uploader.start();
$('#attachment-drag-and-drop').css('border-color', '#dfdfdf');
});
/* Run after adding file */
uploader.bind('FilesAdded', function (up, files) {
var html = '';
var attachmentThumb = "";
plupload.each(files, function (file) {
attachmentThumb += '<div id="holder-' + file.id + '" class="attachment-thumb">' + '' + '</div>';
});
document.getElementById('attachment-thumbs-container').innerHTML += attachmentThumb;
up.refresh();
uploader.start();
});
/* Run during upload */
uploader.bind('UploadProgress', function (up, file) {
document.getElementById("holder-" + file.id).innerHTML = '<span>' + file.percent + "%</span>";
});
/* In case of error */
uploader.bind('Error', function (up, err) {
document.getElementById('attachment-errors-log').innerHTML += "<br/>" + "Error #" + err.code + ": " + err.message;
});
/* If files are uploaded successfully */
uploader.bind('FileUploaded', function (up, file, ajax_response) {
var response = $.parseJSON(ajax_response.response);
if (response.success) {
document.getElementById('attachment-errors-log').innerHTML = "";
let fileType = response.type.split("/");
var attachmentThumbHtml = '<span class="' + fileType[1] + '">' + get_icon_for_extension(fileType[1]) + ' ' + response.post_title + '</span>' +
'<a class="remove-attachment" data-property-id="' + 0 + '" data-attachment-id="' + response.attachment_id + '" href="#remove-attachment" ><i class="fa fa-trash-o"></i></a>' +
'<input type="hidden" class="attachment-id" name="property_attachment_ids[]" value="' + response.attachment_id + '"/>' +
'<span class="loader"><i class="fa fa-spinner fa-spin"></i></span>';
document.getElementById("holder-" + file.id).innerHTML = attachmentThumbHtml;
bindThumbnailEvents(); // bind click event with newly added attachment thumb
} else {
// log response object
console.log(response);
document.getElementById("holder-" + file.id).remove();
document.getElementById('attachment-errors-log').innerHTML = response.reason;
}
});
uploader.bind('FilesAdded', function (up, files) {
var numItems = $('.attachment-thumb').length;
var maxfiles = $('.rh_attachment_drag_and_drop_wrapper').data('max-images');
$('.attachment_limit_left .attachment-uploaded').text(numItems);
if (numItems >= maxfiles) {
$('.rh_attachment_drag_and_drop_wrapper').addClass('hide');
$('.rh_attachment_max_file_limit_message').removeClass('hide');
}
});
/* Bind thumbnails events with newly added attachment thumbs */
var bindThumbnailEvents = function () {
// unbind previous events
$('a.remove-attachment').unbind('click');
// Remove attachments
$('a.remove-attachment').click(function (event) {
event.preventDefault();
var $this = $(this);
var attachment_thumb = $this.closest('.attachment-thumb');
var loader = $this.siblings('.loader');
loader.show();
var removal_request = $.ajax({
url: ajaxURL,
type: "POST",
data: {
property_id: $this.data('property-id'),
attachment_id: $this.data('attachment-id'),
action: "remove_property_attachment",
nonce: uploadNonce
},
dataType: "html"
});
removal_request.done(function (response) {
var result = $.parseJSON(response);
if (result.attachment_removed) {
uploader.removeFile(attachment_thumb);
attachment_thumb.remove();
$('.rh_attachment_drag_and_drop_wrapper').removeClass('hide');
$('.rh_attachment_max_file_limit_message').addClass('hide');
var numItems = $('.attachment-thumb').length;
$('.attachment_limit_left .attachment-uploaded').text(numItems);
} else {
document.getElementById('attachment-errors-log').innerHTML += "<br/>" + "Error : Failed to remove attachment";
}
});
removal_request.fail(function (jqXHR, textStatus) {
alert("Request failed: " + textStatus);
});
uploader.splice();
}); // end of remove attachment thumb click event
}; // end of bind thumbnail events
bindThumbnailEvents(); // run it first time - required for property edit page
}
})(jQuery);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment