Uploade user image in wordpress using json api - wordpress

I am developing the mobile app using WordPress database. I created a user and changing user details using JSON API. But I don't know how to upload user image from mobile to WordPress database using API. Can anyone help me out?

Try this code. I'm using this code for upload user profile image in API
you have to convert image to base64_encode in mobile and send to API
<?php
$password = esc_attr( $password );
$random_password = wp_generate_password( 12, false );
$email = sanitize_email( $useremail );
$first_name = sanitize_text_field( $firstname );
$phoneno = sanitize_text_field( $phoneno );
$type = sanitize_text_field( $type );
$imgdata = base64_decode($data["avatar"]);
$userdata = array(
'user_login' => $email,
'user_email' => $email,
'user_pass' => $password,
'role' => 'customer',
'user_nicename' => $first_name,
'first_name' => $first_name,
'last_name' => '',
);
$new_user = wp_insert_user ( $userdata );
$f = finfo_open();
$mime_type = finfo_buffer($f, $imgdata, FILEINFO_MIME_TYPE);
$type_file = explode('/', $mime_type);
$avatar = time() . '.' . $type_file[1];
$uploaddir = wp_upload_dir();
$myDirPath = $uploaddir["path"];
$myDirUrl = $uploaddir["url"];
file_put_contents($uploaddir["path"].'/'.$avatar,$imgdata);
$filename = $myDirUrl.'/'.basename( $avatar );
$wp_filetype = wp_check_filetype(basename($filename), null );
$uploadfile = $uploaddir["path"] .'/'. basename( $filename );
$attachment = array(
"post_mime_type" => $wp_filetype["type"],
"post_title" => preg_replace("/\.[^.]+$/", "" , basename( $filename )),
"post_content" => "",
"post_status" => "inherit",
'guid' => $uploadfile,
);
require_once(ABSPATH . '/wp-load.php');
require_once(ABSPATH . 'wp-admin' . '/includes/file.php');
require_once(ABSPATH . 'wp-admin' . '/includes/image.php');
$attachment_id = wp_insert_attachment( $attachment, $uploadfile );
$attach_data = wp_generate_attachment_metadata( $attachment_id, $uploadfile );
wp_update_attachment_metadata( $attachment_id, $attach_data );
update_post_meta($attachment_id,'_wp_attachment_wp_user_avatar',$new_user);
update_user_meta($new_user, 'wp_user_avatar', $attachment_id);

Related

Generate WordPress Post Tittle from ACF Fields

I am trying to generate a custom post title from two ACF fields. I have first_name and last_name but it will only generate the last name and does it twice:
/contacts/deere-deere/
Here's my function:
function update_contacts_title( $value, $post_id, $field ) {
$first_name = get_field('first_name', $post_id). ' ' . $value;
$last_name = get_field('last_name', $post_id). ' ' . $value;
$title = $first_name .' - '. $last_name;
$slug = sanitize_title( $title );
$postdata = array(
'ID' => $post_id,
'post_title' => $title,
'post_type' => 'contacts',
'post_name' => $slug
);
wp_update_post( $postdata );
return $value;
}
add_filter('acf/update_value/name=first_name', 'update_contacts_title', 10, 3);
add_filter('acf/update_value/name=last_name', 'update_contacts_title', 10, 3);
If I modify this line down like so, then it will generate the first_name but only once:
/contacts/john/
//Create new title based on ACF Fields
function update_contacts_title( $value, $post_id, $field ) {
$first_name = get_field('first_name', $post_id). ' ' . $value;
$last_name = get_field('last_name', $post_id). ' ' . $value;
//$title = $first_name .' - '. $last_name;
$title = $first_name;
$slug = sanitize_title( $title );
$postdata = array(
'ID' => $post_id,
'post_title' => $title,
'post_type' => 'contacts',
'post_name' => $slug
);
wp_update_post( $postdata );
return $value;
}
add_filter('acf/update_value/name=first_name', 'update_contacts_title', 10, 3);
//add_filter('acf/update_value/name=last_name', 'update_contacts_title', 10, 3);
This is really confusing me as to why it won't recognize both the first name and last name.
Any suggestions would be extremely helpful, thank you all.
You have "first_name" for both the names I believe.
$first_name = get_field('first_name', $post_id). ' ' . $value;
$last_name = get_field('first_name', $post_id). ' ' . $value;
Here's the answer I figured out after I remembered that I have the first_name and last_name in a group, which requires a repeater field in the function:
function update_contacts_title($post_id) {
if( have_rows('contact_info') ):
while( have_rows('contact_info') ): the_row();
$first_name = get_sub_field('first_name', $post_id);
$last_name = get_sub_field('last_name', $post_id);
$title = $first_name . '-' . $last_name;
$slug = sanitize_title( $title );
endwhile;
endif;
$postdata = array(
'ID' => $post_id,
'post_title' => $title,
'post_type' => 'contacts',
'post_name' => $slug
);
wp_update_post( $postdata );
}
add_filter('acf/save_post', 'update_contacts_title', 10, 3);

How to set the featured image of a post from the Media Library

If I create a post with this function:
function write_post_with_featured_image( $post_title, $categories ) {
$category_names_array = explode( ",", $categories );
$category_ids = array( );
foreach ( $category_names_array as $category_name ) {
$category_id = get_cat_ID( $category_name );
array_push( $category_ids, $category_id );
}
// Create post object
$my_post = array(
'post_title' => wp_strip_all_tags( $post_title ),
'post_status' => 'publish',
'post_author' => 1,
'post_category' => $category_ids,
);
// Insert the post into the database
$post_id = wp_insert_post( $my_post );
echo "post_id: " . $post_id;
}
How can I set it's featured image already existing in the Media Library?
Hopefully everyone will enjoy this function that creates a post and set's it's featured image from the Media Library:
function write_post_with_featured_image($post_title, $categories, $image_in_library_url) {
$category_names_array = explode(",", $categories);
$category_ids = array();
foreach ($category_names_array as $category_name) {
$category_id = get_cat_ID($category_name);
array_push($category_ids, $category_id);
}
// Create post object
$my_post = array(
'post_title' => wp_strip_all_tags($post_title),
'post_status' => 'publish',
'post_author' => 1,
'post_category' => $category_ids
);
// Insert the post into the database
$post_id=wp_insert_post( $my_post );
echo "post_id:" . $post_id;
//Get Image Attachment Id
$attachment_id = attachment_url_to_postid( $image_in_library_url );
echo "attachment_id:" . $attachment_id;
// And finally assign featured image to post
set_post_thumbnail( $post_id, $attachment_id );
echo "featured image added";
}
}
$post_title = 'My Super Post';
$categories = 'Category1,Category2';
$image_in_library_url = "http://localhost/wp-content/uploads/2018/06/my-super-image.jpg";
write_post_with_featured_image($post_title,$categories,$image_in_library_url);

How to make post attachments available on save_post action?

I have the following codes to insert a post from frontend:
if(!function_exists('zabeelAddMedicalHistory')){
function zabeelAddMedicalHistory()
{
$nonce = $_POST['nonce'];
if ( ! wp_verify_nonce( $nonce, 'create-report-nonce' ) ) {
die( 'Security check' );
} else {
$postID = wp_insert_post(array(
'post_type' => 'report',
'post_title' => wp_strip_all_tags( $_POST['postTitle'] ),
'post_status' => 'publish',
'post_content' => $_POST['postContent']
));
}
if ($postID) {
add_post_meta($postID, '_report_patient_id', $_REQUEST['_report_patient_id'], true);
if ($_FILES['postFile']) {
if ($_FILES['postFile']['error'] !== UPLOAD_ERR_OK) __return_false();
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
$uploadedFile = media_handle_upload('postFile', $postID );
if ( !is_wp_error( $uploadedFile ) ) {
$filename = $uploadedFile['file'];
$attachment = array(
'post_mime_type' => $uploadedFile['type'],
'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ),
'post_content' => '',
'post_status' => 'inherit',
'guid' => $uploadedFile['url']
);
$attachment_id = wp_insert_attachment( $attachment, $uploadedFile['url'] );
$attachment_data = wp_generate_attachment_metadata( $attachment_id, $filename );
wp_update_attachment_metadata( $attachment_id, $attachment_data );
}
}
}
wp_redirect( wp_get_referer() );
exit;
}
add_action('wp_ajax_zabeelAddMedicalHistory', 'zabeelAddMedicalHistory');
add_action('wp_ajax_nopriv_zabeelAddMedicalHistory', 'zabeelAddMedicalHistory');
}
And I am sending an email to the user on save_post action after the post is saved. But at the time when the post is saved and the save_post action comes into play, the attachments are not yet available on the save_post action. I have also tried delaying the priority of the save_post action but still the attachment could not be made available.
It seems you can hook to publish_post.
maybe this question can guide you on the right direction:
https://wordpress.stackexchange.com/questions/192258/execute-action-after-post-is-saved-with-all-related-post-meta-records-data

Add attachment metadata after wp_insert_attachment()

I am writing a plugin that saves email attachments to a custom disk folder and then adds them as attachments to a custom post type. This all works correctly so far, but I need to save a couple of metadata values. The metadata will always be the same (so far) and it needs to be on any attachment filetype (.zip, .jpg, .txt, etc)
Can anyone tell me how to add a metadata key/value in this code:
$filename = $attachment['filename'];
$mimetype = $attachment['mimetype'];
$data = $attachment['data'];
$upload = wp_upload_bits( $filename, null, $data );
if ( ! $upload['error'] ) {
$attachment_data = array(
'guid' => trailingslashit( $upload['url']) . basename( $filename ),
'post_mime_type' => $mimetype,
'post_parent' => $post_id,
'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ),
'post_content' => '',
'post_status' => 'inherit',
);
$attachment_id = wp_insert_attachment( $attachment_data, $upload['file'], $post_id );
if ( is_wp_error( $attachment_id ) ) {
return false;
} else {
$attach_data = wp_generate_attachment_metadata( $attachment_id, $upload['file'] );
wp_update_attachment_metadata( $attachment_id, $attach_data );
return true;
}
}
$attach_data above always returns empty.

WordPress insert_attachment set post_author

I want to post attachments from the front end in WordPress, here is my code which works:
Form process:
global $post;
if ( $_FILES ) {
$files = $_FILES['upload_attachment'];
foreach ($files['name'] as $key => $value) {
if ($files['name'][$key]) {
$file = array(
'name' => $files['name'][$key],
'type' => $files['type'][$key],
'tmp_name' => $files['tmp_name'][$key],
'error' => $files['error'][$key],
'size' => $files['size'][$key]
);
$_FILES = array("upload_attachment" => $file);
foreach ($_FILES as $file => $array) {
$newupload = insert_attachment($file,0);
}
}
}
}
Function to process uploads:
function insert_attachment($file_handler,$post_id,$setthumb='false') {
// check to make sure its a successful upload
if ($_FILES[$file_handler]['error'] !== UPLOAD_ERR_OK) __return_false();
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
$attach_id = media_handle_upload( $file_handler, $post_id );
if ($setthumb) update_post_meta($post_id,'_thumbnail_id',$attach_id);
return $attach_id;
}
I would like to set the post_author of the attachment, as currently is defaults to the current logged in user.
I have tried adding the following into the function, but it doesn't seem to work:
$my_post = array(
'ID' => $attach_id,
'post_author' => 2
);
wp_update_post( $my_post );
Not quite sure what had happened, i retried this and seemed to of worked! Just wanted to update incase anyone else has the same issue!
$my_post = array(
'ID' => $attach_id,
'post_author' => 2
);
wp_update_post( $my_post );
if ($setthumb) {
update_post_meta($post_id, '_thumbnail_id', $attach_id);
}
Well according to wp_update_post(codex) you have to pass the POST_ID and I am not sure if your $attach_id is the post ID, according to update_post_meta($post_id, '_thumbnail_id', $attach_id); Pass the $post_id
$my_post = array(
'ID' => $post_id,
'post_author' => 2
);
wp_update_post( $my_post );

Resources