admin-multiple-pdf-import.php:
<h1 class="wp-heading-inline">Add Multiple Dateien</h1>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<div class = "col-md-6 upload-form">
<div class= "upload-response"></div>
<div class = "form-group">
<label><?php __('Select Files:', 'cvf-upload'); ?></label>
<input type = "file" name = "files[]" class = "files-data form-control" multiple style="height: auto;" />
</div>
<div class = "form-group">
<input type = "submit" value = "Upload" class = "btn btn-primary btn-upload" />
</div>
<div class="form-group">
<div class="progress">
<div class="progress-bar progress-bar-success myprogress" role="progressbar" style="width:0%">0%</div>
</div>
</div>
</div>
<script type = "text/javascript">
jQuery(document).ready(function($) {
$('.myprogress').css('width', '0');
$('.upload-response').text('');
// When the Upload button is clicked...
$('body').on('click', '.upload-form .btn-upload', function(e){
$('.upload-response').text('Uploading in progress...');
e.preventDefault;
var fd = new FormData();
var files_data = $('.upload-form .files-data'); // The <input type="file" /> field
// Loop through each data and create an array file[] containing our files data.
$.each($(files_data), function(i, obj) {
$.each(obj.files,function(j,file){
fd.append('files[' + j + ']', file);
})
});
// our AJAX identifier
fd.append('action', 'cvf_upload_files');
$.ajax({
xhr: function () {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function (evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
percentComplete = parseInt(percentComplete * 100);
console.log(percentComplete);
$('.myprogress').text(percentComplete + '%');
$('.myprogress').css('width', percentComplete + '%');
}
}, false);
return xhr;
},
type: 'POST',
url: '<?php echo admin_url( 'admin-ajax.php' ); ?>',
data: fd,
contentType: false,
processData: false,
success: function(response){
$('.upload-response').html(response); // Append Server Response
}
});
});
});
</script>
functions.php
add_action('admin_menu', 'wpdocs_register_my_custom_submenu_page');
function wpdocs_register_my_custom_submenu_page() {
add_submenu_page(
'edit.php?post_type=fa_files',
'Add Multiple',
'Add Multiple',
'manage_options',
'add-files',
'wpdocs_addnew_multiple_callback' );
}
function wpdocs_addnew_multiple_callback() {
include("admin-multiple-pdf-import.php");
}
add_action('wp_ajax_cvf_upload_files', 'cvf_upload_files');
add_action('wp_ajax_nopriv_cvf_upload_files', 'cvf_upload_files'); // Allow front-end submission
function cvf_upload_files(){
$parent_post_id = isset( $_POST['post_id'] ) ? $_POST['post_id'] : 0; // The parent ID of our attachments
$valid_formats = array("pdf"); // Supported file types
$wp_upload_dir = wp_upload_dir();
$path = $wp_upload_dir['path'] . '/';
$count = 0;
$attachments = get_posts( array(
'post_type' => 'attachment',
'posts_per_page' => -1,
'post_parent' => $parent_post_id,
'exclude' => get_post_thumbnail_id() // Exclude post thumbnail to the attachment count
) );
// Image upload handler
if( $_SERVER['REQUEST_METHOD'] == "POST" ){
foreach ( $_FILES['files']['name'] as $f => $name ) {
$extension = pathinfo( $name, PATHINFO_EXTENSION );
// Generate a randon code for each file name
$new_filename = $_FILES['files']['name'][$f];
if ( $_FILES['files']['error'][$f] == 4 ) {
continue;
}
if ( $_FILES['files']['error'][$f] == 0 ) {
/* // Check if image size is larger than the allowed file size
if ( $_FILES['files']['size'][$f] > $max_file_size ) {
$upload_message[] = "$name is too large!.";
continue; */
// Check if the file being uploaded is in the allowed file types
// } elseif( ! in_array( strtolower( $extension ), $valid_formats ) ){
if( ! in_array( strtolower( $extension ), $valid_formats ) ){
$upload_message[] = "$name is not a valid format";
continue;
} else{
// If no errors, upload the file...
if( move_uploaded_file( $_FILES["files"]["tmp_name"][$f], $path.$new_filename ) ) {
$count++;
$filename = $path.$new_filename;
$filetype = wp_check_filetype( basename( $filename ), null );
$wp_upload_dir = wp_upload_dir();
$attachment = array(
'guid' => $wp_upload_dir['url'] . '/' . basename( $filename ),
'post_mime_type' => $filetype['type'],
'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ),
'post_content' => '',
'post_status' => 'inherit'
);
// Insert attachment to the database
$attach_id = wp_insert_attachment( $attachment, $filename, $parent_post_id );
require_once( ABSPATH . 'wp-admin/includes/image.php' );
// Generate meta data
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );
}
}
//$fileName=$_FILES['UploadPDF']['name'];
$filebase= basename($new_filename, ".pdf");
$pdflname=explode('_', $filebase);
//print_r($pdflname);
$kampID=get_post_by_title($pdflname[0]);
if(empty($kampID)) {
$kampID = wp_insert_post(array (
'post_type' => 'fa_campaigns',
'post_title' => $pdflname[0],
'post_content' => $pdflname[0],
'post_status' => 'publish',
'comment_status' => 'closed', // if you prefer
'ping_status' => 'closed', // if you prefer
));
}
$post_id = wp_insert_post(array (
'post_type' => 'fa_files',
'post_title' => $pdflname[1].'x'.$pdflname[2],
'post_content' => $pdflname[1].'x'.$pdflname[2],
'post_status' => 'publish',
'comment_status' => 'closed', // if you prefer
'ping_status' => 'closed', // if you prefer
));
if($post_id) {
// insert post meta
add_post_meta($post_id, 'kampagne', $kampID);
add_post_meta($post_id, 'filewidth', $pdflname[1]);
add_post_meta($post_id, 'fileheight', $pdflname[2]);
add_post_meta($post_id, 'farbigkeit', $pdflname[3]);
add_post_meta($post_id, 'datei', $attach_id);
}
}
}
}
// Loop through each error then output it to the screen
if ( isset( $upload_message ) ) :
foreach ( $upload_message as $msg ){
printf( __('<p class="bg-danger">%s</p>', 'wp-trade'), $msg );
}
endif;
// If no error, show success message
if( $count != 0 ){
printf( __('<p class = "bg-success">%d files added successfully!</p>', 'wp-trade'), $count );
}
exit();
}
function get_post_by_title($page_title, $post_type ='fa_campaigns' , $output = OBJECT) {
global $wpdb;
$post = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_title = %s AND post_type= %s", $page_title, $post_type));
if ( $post )
return $post;
return null;
}
Comments
Post a Comment