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
Related
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);
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);
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.
Hello Friends I used to set post thumbnail programmatically.
this is my code.
foreach ($csv as $key => $value) {
$filename = "wp-content/uploads/images/".$value[8].".jpg";
$wp_filetype = wp_check_filetype(basename($filename), null );
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
'post_content' => 'this is the first project file.',
'post_status' => 'Published'
);
$my_post = array(
'post_title' => $value[0],
'post_content' => $value[2],
'post_status' => 'publish',
'post_author' => 1,
'post_type' => 'post_staff'
);
$post_id = wp_insert_post( $my_post );
$attach_id = wp_insert_attachment( $attachment, $filename,$post_id);
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );
add_post_meta($post_id, '_thumbnail_id', $attach_id);
update_post_meta( $post_id, '_staff_name', $value[1] );
update_post_meta( $post_id, '_staff_city', $value[3] );
update_post_meta( $post_id, '_staff_postal_code', $value[4] );
update_post_meta( $post_id, '_staff_direct_line', $value[5] );
update_post_meta( $post_id, '_staff_fax', $value[6] );
update_post_meta( $post_id, '_staff_email', $value[7] );
$tagd = array( 9 );
wp_set_post_terms( $post_id, $tagd, 'department' );
if($value[3] == "St. John's, NL"){
$tagl = array( 8 );
}else if($value[3] == "Corner Brook"){
$tagl = array( 7 );
}
wp_set_post_terms( $post_id, $tagl, 'location' );
if(set_post_thumbnail( $post_id, $attach_id )){
echo "image set";
}
}
This is working fine but the imported feature image with size 1x1 width = 1 and height = 1
why it takes width and height is 1 automatically please help.
when i trying to get image using get_the_post_thumbnail the return image.
image is found but by default the image width = 1 and height = 1 take.
this is my code.
get_the_post_thumbnail( get_the_ID(), array(250,165))
Thank you.
This Function is used to import post with image in wordpress.
function fetch_media($file_url, $post_id) {
require_once(ABSPATH . 'wp-load.php');
require_once(ABSPATH . 'wp-admin/includes/image.php');
global $wpdb;
if(!$post_id) {
return false;
}
//directory to import to
$artDir = 'wp-content/uploads/importedmedia/';
//if the directory doesn't exist, create it
if(!file_exists(ABSPATH.$artDir)) {
mkdir(ABSPATH.$artDir);
}
//rename the file... alternatively, you could explode on "/" and keep the original file name
$extpop = explode(".", $file_url);
$ext = array_pop($extpop);
$new_filename = 'blogmedia-'.$post_id.".".$ext; //if your post has multiple files, you may need to add a random number to the file name to prevent overwrites
if (#fclose(#fopen($file_url, "r"))) { //make sure the file actually exists
copy($file_url, ABSPATH.$artDir.$new_filename);
$siteurl = get_option('siteurl');
$file_info = getimagesize(ABSPATH.$artDir.$new_filename);
//create an array of attachment data to insert into wp_posts table
$artdata = array();
$artdata = array(
'post_author' => 1,
'post_date' => current_time('mysql'),
'post_date_gmt' => current_time('mysql'),
'post_title' => $new_filename,
'post_status' => 'inherit',
'comment_status' => 'closed',
'ping_status' => 'closed',
'post_name' => sanitize_title_with_dashes(str_replace("_", "-", $new_filename)), 'post_modified' => current_time('mysql'),
'post_modified_gmt' => current_time('mysql'),
'post_parent' => $post_id,
'post_type' => 'attachment',
'guid' => $siteurl.'/'.$artDir.$new_filename,
'post_mime_type' => $file_info['mime'],
'post_excerpt' => '',
'post_content' => ''
);
$uploads = wp_upload_dir();
$save_path = $uploads['basedir'].'/importedmedia/'.$new_filename;
//insert the database record
$attach_id = wp_insert_attachment( $artdata, $save_path, $post_id );
//generate metadata and thumbnails
if ($attach_data = wp_generate_attachment_metadata( $attach_id, $save_path)) {
wp_update_attachment_metadata($attach_id, $attach_data);
}
//optional make it the featured image of the post it's attached to
$rows_affected = $wpdb->insert($wpdb->prefix.'postmeta', array('post_id' => $post_id, 'meta_key' => '_thumbnail_id', 'meta_value' => $attach_id));
}
else {
return false;
}
return true;
}
Pass value to this function like.
$file_name = 'full path of existing image';
$post_id = '1';
fetch_media($filename,$post_id);
Thank you.
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 );