Skip to content

Instantly share code, notes, and snippets.

@yasaryousuf
Created May 12, 2018 06:24
Show Gist options
  • Save yasaryousuf/ff6a794b4a563de8c1b09fcf64568f20 to your computer and use it in GitHub Desktop.
Save yasaryousuf/ff6a794b4a563de8c1b09fcf64568f20 to your computer and use it in GitHub Desktop.
<?php
public function pfmEditProfile()
{
if (!isset($_POST['pfmEditProfile']) || !wp_verify_nonce($_POST['pfmEditProfile'], 'pfmEditProfile-nonce')) {
die("You are not allowed to submit data.");
}
if ( ! function_exists( 'wp_handle_upload' ) ) {
require_once( ABSPATH . 'wp-admin/includes/file.php' );
}
$file_return = wp_handle_upload( $_FILES['profile_picture'], array('test_form' => false ) );
if( isset( $file_return['error'] ) || isset( $file_return['upload_error_handler'] ) ) {
return false;
}
$attachment_id = (new PfmUpload())->attachFile($file_return);
if (empty($attachment_id)) {
return false;
}
update_user_meta( get_current_user_id(), 'photo', $attachment_id );
wp_redirect($_POST['_wp_http_referer']);
exit();
}
public static function attachFile(array $file, $post_id = false)
{
$url = $file['url'];
$type = $file['type'];
$file = $file['file'];
$title = preg_replace('/\.[^.]+$/', '', basename($file));
$parent = (int) absint($post_id) > 0 ? absint($post_id) : 0;
$attachment = array(
'post_mime_type' => $type,
'guid' => $url,
'post_parent' => $parent,
'post_title' => $title,
'post_content' => '',
);
$id = wp_insert_attachment($attachment, $file, $parent);
if (!is_wp_error($id)) {
require_once ABSPATH . 'wp-admin/includes/image.php';
$data = wp_generate_attachment_metadata($id, $file);
wp_update_attachment_metadata($id, $data);
}
return $id;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment