Skip to content

Instantly share code, notes, and snippets.

@kingjmaningo
Created February 27, 2023 01:36
Show Gist options
  • Save kingjmaningo/2d4f7c6caa56ab6645009539d9e801ba to your computer and use it in GitHub Desktop.
Save kingjmaningo/2d4f7c6caa56ab6645009539d9e801ba to your computer and use it in GitHub Desktop.
Custom file upload with nonce - Wordpress
<!-- Image preview Script -->
<script>
jQuery(document).ready(function($){
function imagePreview(uploader) {
if (uploader.files && uploader.files[0]) {
$("#display-upload-image").attr("src", window.URL.createObjectURL(uploader.files[0]));
}
}
$("#sample_image").change(function() {
imagePreview(this);
});
});
</script>
<?php $get_image = get_option('sample_image') ? : ''; ?>
<form id="ct-theme-settings-form" method="POST" enctype="multipart/form-data">
<?php wp_nonce_field( 'save_upload_form_sample', 'save_upload_form_sample_fields' ); ?>
<?php if (wp_attachment_is('image',$get_image)) : ?>
<img id="display-upload-image" src="<?php echo wp_get_attachment_url( $get_image ); ?>" width="100" height="100" style="object-fit: contain; display: block; margin-bottom: 10px;">
<?php endif; ?>
<input style="width: 25em;" name="sample_image" type="file" id="sample_image" value="">
<input type="submit" id="submit" value="Save">
</form>
<?php
function upload_image_session() {
if( isset( $_POST['save_upload_form_sample_fields'] ) && wp_verify_nonce( $_POST['save_upload_form_sample_fields'], 'save_upload_form_sample' )) {
//$_POST['ct-save-settings-error'] = false;
if( isset( $_FILES["sample_image"] ) && !empty( $_FILES["sample_image"] && !empty( $_FILES["sample_image"]["tmp_name"] ) ) ) {
$upload_logo = wp_upload_bits( $_FILES["sample_image"]["name"], null, file_get_contents( $_FILES["sample_image"]["tmp_name"] ) );
if ( !$upload_logo['error'] ) {
$filename = $upload_logo['file'];
$wp_filetype = wp_check_filetype($filename, null);
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => sanitize_file_name($filename),
'post_content' => '',
'post_status' => 'inherit'
);
$attachment_id = wp_insert_attachment($attachment, $filename);
// $attachment_data = wp_generate_attachment_metadata( $attachment_id, $filename );
//$logo_url = wp_get_attachment_url( $attachment_id );
update_option( 'sample_image', $attachment_id );
}
}
update_option( 'ct_theme_settings', $_POST);
}
}
add_action( 'init', 'upload_image_session');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment