I want to upload pdf files via posts using metaboxes. I have this code:
if ( is_admin() ) {
add_action( 'load-post.php', 'call_MetaBoxClass' );
add_action( 'load-post-new.php', 'call_MetaBoxClass' );
}
function call_MetaBoxClass() {
new MetaBoxClass();
}
class MetaBoxClass {
private $post_types = array( 'post', 'page' );
public function __construct() {
add_action( 'add_meta_boxes', array( $this, 'add_metaa_box' ) );
add_action( 'save_post', array( $this, 'save' ) );
}
public function add_metaa_box( $post_type ) {
add_action('post_edit_form_tag', 'update_edit_form');
if ( in_array( $post_type, $this->post_types ) ) {
add_meta_box(
'MetaBoxId',
__( 'MetaBox', 'textdomain' ),
array( $this, 'render_meta_box_content' ),
$post_type,
'side'
);
}
}
public function save( $post_id) {
$nonce = @$_POST['MetaBoxNonce_name'];
if ( ! wp_verify_nonce( $nonce, 'MetaBoxNonce_action' ) ) {
return $post_id;
}
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
return $post_id;
}
if ( 'page' == $_POST['post_type'] && ! current_user_can( 'edit_page', $post_id )) {
return $post_id;
}
else if (! current_user_can( 'edit_post', $post_id )){
return $post_id;
}
//----------------------------------
if(!empty($_FILES['eventEsbat']['name'])) {
$supported_types = array('application/pdf');
$arr_file_type = wp_check_filetype(basename($_FILES['eventEsbat']['name']));
$uploaded_type = $arr_file_type['type'];
if(in_array($uploaded_type, $supported_types)) {
$upload = wp_upload_bits($_FILES['eventEsbat']['name'], null, file_get_contents($_FILES['eventEsbat']['tmp_name']));
if(isset($upload['error']) && $upload['error'] != 0) {
wp_die('There was an error uploading your file. The error is: ' . $upload['error']);
} else {
add_post_meta($post_id, 'eventEsbat', $upload);
update_post_meta($post_id, 'eventEsbat', $upload);
}
} else {
wp_die("The file type that you've uploaded is not a PDF.");
}
}
}
public function render_meta_box_content( $post ) {
wp_nonce_field( 'MetaBoxNonce_action', 'MetaBoxNonce_name' );
?>
<p>pdf file:</p>
<input type="file" name="eventEsbat" class="eventEsbat" size="25"/>
<?php
}
}
function update_edit_form() {
echo ' enctype="multipart/form-data"';
}
now if in post page I don't upload any file and only make other changes and then click on update or publish button everything goes well and MetaBoxClass::save() will execute.
but if I upload any file then nothing will save even post title don't save too and MetaBoxClass::save() will not execute.
now what section I must to change to solve the problem ?